除以任何数组元素时给出余数 K 的最小素数
给定一个大小为N的整数数组arr[]和一个整数K ,任务是找到最小的素数,使得当它除以数组的任何元素时得到余数K。
注意:素数应在 [1, 10 6 ] 范围内
例子:
Input: arr[]= {3, 4, 5}, K = 1
Output: 61
Explanation: The smallest prime that satisfies the condition is 61.
61%3 = 1, 61%4 = 1 and 61%5 =1.
Input: arr[] = {2, 4, 5}, K = 3
Output: -1
Explanation: The output should not be possible because
no number can have remainder 3 when divided by 2.
Input: arr[] = {10, 4, 5}, K = 3
Output: 23
Explanation: The smallest prime that satisfies the condition is 23.
23%10 = 3, 23%4 = 3 and 23%5 = 3
方法:解决问题的思路如下:
The LCM of numbers is the smallest number divisible by all the other numbers. So find the LCM of the array and check for each multiple of the LCM whether LCM + K is prime or not to get the smallest prime which gives the remainder as K.
If any element of the array is smaller than K then solution is not possible. Because no number can have a remainder higher than itself when dividing a number.
按照以下步骤进行上述操作:
- 首先,找到数组中所有元素的lcm (比如 lcm)。
- 迭代每个小于或等于 10 6的lcm倍数:
- 检查 ( lcm + K ) 对于 lcm 的每个倍数是否为素数
- 如果条件成立,则返回K和 lcm 的当前倍数之和作为 minimum_prime。
- 如果没有找到素数,则返回-1 。
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to find the
// gcd of two integers
long long gcd(long long int a,
long long int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to check if an integer
// is prime or not
bool checkPrime(long long n)
{
long long ub = sqrt(n);
for (long long i = 2; i <= ub; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
// Function to find the smallest prime
// that gives the same remainder when
// divided by any of the element in arr.
long long smallestPrime(vector arr,
int q)
{
// Finding the lcm of the array
long long lcm = arr[0];
for (int i : arr) {
lcm = (lcm * i) / (gcd(i, lcm));
}
// Edge case, if the value of any
// in the array is less than remainder
for (auto i : arr) {
if (i < q)
return -1;
}
// Check whether (lcm + remainder) is
// prime or not, for all multiples of lcm
for (long long i = lcm; i <= 1e9;
i += lcm) {
if (checkPrime(i + q)) {
return i + q;
}
}
// If any prime satisfying the
// condition is not found
// simply return -1;
return -1;
}
// Driver code
int main()
{
vector arr = { 2, 5, 4 };
int q = 3;
cout << smallestPrime(arr, q);
return 0;
}
23
时间复杂度: O(N * logD + (M/lcm)*sqrt(M)) 其中 D 是数组的最大值,M 是素数的可能上限,lcm 是所有数组元素的 LCM
辅助空间: O(1)