Smallest integer > 1 which divides every element of the given array: Using C++

C++ProgrammingServer Side Programming

In this article, we are given integers in an array, and we must find the smallest number which is greater than 1 that divides all the elements in the array. For example, let us consider a sample array [30, 90, 15, 45, 165].

vector<int> arr = {30, 90, 15, 45, 165};
result = solve(arr);

Now we can find the array's GCD(greatest common divisor). If it comes out to be 1 that means that only 1 can divide the whole array, and we can return -1 or "Not possible." If it's an integer, then this integer divides the whole array. Still, this integer might not be the smallest integer that divides the whole array. Interestingly, the factors of this integer also divide the complete array, which makes sense. So if we can find the minimum factor of this integer(GCD), we get our smallest integer which divides the whole array. So, in short, we need to find the GCD of the array, and then the minimum factor of the GCD is our answer.

Example

The following C++ code finds a smallest integer greater than 1 that divides all the elements of an array. This can be done by finding the GCD for the list of elements −

#include <iostream> #include <vector> #include <algorithm> using namespace std; int divisor(int x) { if (x%2 == 0) { return 2; } for (int i=3;i*i<=x;i+=2) { if (x%i == 0) { return i; } } return x; } int solve(vector<int> arr) { int gcd = 0; for (int i=0;i<arr.size();i++) { gcd = __gcd(gcd, arr[i]); } return divisor(gcd); } int main() { vector<int> arr = {30, 90, 15, 45, 165}; cout << solve(arr); return 0; }

Output

3

Example

If there are a lot of queries, finding the prime factor for numbers will be repetitive. Using a sieve, we can calculate the prime factors for numbers.

Another implementation in C++ for finding the smallest number greater than 1, is as follows −

#include <iostream> #include <vector> #include <algorithm> using namespace std; const int MAX = 100005; vector<int> prime(MAX, 0); void sieve() { prime[0] = 1; prime[1] = -1; for (int i=2; i*i<MAX;i++) { if (prime[i] == 0) { for (int j=i*2;j<MAX;j+=i) { if (prime[j] == 0) { prime[j] = i; } } } } for (int i=2; i<MAX;i++) { if (!prime[i]) { prime[i] = i; } } } int solve(vector<int> arr) { int gcd = 0; for (int i=0; i<arr.size();i++) { gcd = __gcd(gcd, arr[i]); } return prime[gcd]; } int main() { sieve(); vector<int> arr = { 30, 90, 15, 45, 165 }; cout << solve(arr); return 0; }

Output

3

Conclusion

We have used the sqrt(n) method to get the minimum factor. This can be optimized, and I leave that for you to try. The time complexity is O(sqrt(n)). In the second approach, the time complexity will be of the sieve, which is O(nlog(log(n))). Note that we can find the sieve up to a limit, which we set through the MAX global variable.

raja
Updated on 10-Aug-2022 09:51:06

Advertisements