![]() |
VOOZH | about |
You are given an array of N positive integers. Your task is to find two integers such that their greatest common divisor is as large as possible.
Example:
Input: N = 5, arr[] = {3, 14, 15, 7, 9}
Output: 7
Explanation: GCD(14, 7)=7 which is the maximum possible among all the pairsInput: arr[] = {1, 12, 15, 3, 8}
Output: 4
Explanation: GCD(12, 8)=4 which is the maximum possible among all the pairs
Approach: To solve the problem, follow the below idea:
First count the occurrences of each integer in the array. This is done using a count array, where the index represents the integer and the value at that index represents the number of occurrences of that integer.
Then, to find the largest GCD, iterate from the largest possible integer down to 1 and checking if there are at least two multiples of the current integer in the array (since the GCD of two numbers can be at most the smaller number). If there are, that means the current integer is the largest GCD, so it is returned as the result.
Step-by-step algorithm:
Below is the implementation of the algorithm:
7
Time Complexity: O(N * log(N)), where N is the maximum element in the array arr[].
Auxiliary Space: O(N)