![]() |
VOOZH | about |
Given an array of integers arr[] of size N and an integer K, the task is to find the smallest prime such that it gives remainder K when it is divided by any of the elements of the array.
Note: The prime number should be in the range [1, 106]
Examples:
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
Approach: The idea to solve the problem is mentioned below:
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.
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.
Follow the below steps for the above:
Below is the implementation of the above approach:
-1
Time Complexity: O(N * logD + (M/lcm)*sqrt(M)) where D is max of array, M is upper possible limit of prime, lcm is LCM of all array elements
Auxiliary Space: O(1)