Given an integer N greater than 2, the task is to find an element M such that GCD(N, M) is maximum.
Input: N = 10
gcd(1, 10), gcd(3, 10), gcd(7, 10), gcd(9, 10) is 1,
gcd(2, 10), gcd(4, 10), gcd(6, 10), gcd(8, 10) is 2,
gcd(5, 10) is 5 which is maximum.
Input: N = 21
gcd(7, 21) is maximum among all the integers from 1 to 21.
Naive Approach: The simplest approach is to loop through all the numbers in the range [1, N-1] and find GCD of each number with N. The number which given maximum GCD with N is the required result.
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, we observe that the GCD of two numbers will be definitely one of its divisors in the range [1, N-1]. And, GCD will be maximum if the divisor is maximum.
Therefore, the idea is to find all the divisors of N and store a maximum of those divisors which is the required result.
Below is the implementation of the above approach:
Time Complexity: O(log2N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find a positive number M such that gcd(N^M, N&M) is maximum
- Pair of integers having least GCD among all given pairs having GCD exceeding K
- Smallest subsequence having GCD equal to GCD of given array
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K
- Find the number of pairs such that their gcd is equals to 1
- Divide N into K unique parts such that gcd of those parts is maximum
- Given GCD G and LCM L, find number of possible pairs (a, b)
- Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
- Find pair with maximum GCD in an array
- Find the maximum GCD of the siblings of a Binary Tree
- Find pair with maximum GCD for integers in range 2 to N
- Find maximum GCD value from root to leaf in a Binary tree
- Maximum GCD of N integers with given product
- Maximum GCD from Given Product of Unknowns
- Maximum possible GCD after replacing at most one element in the given array
- Count number of subsets of a set with GCD equal to a given number
- Find any pair with given GCD and LCM
- Find two numbers whose sum and GCD are given
- Queries to update a given index and find gcd in range
- Convert the array such that the GCD of the array becomes 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.