Maximize GCD of all possible pairs from 1 to N
Last Updated :
15 Jun, 2022
Given an integer N (> 2), the task is to find the maximum GCD among all pairs possible by the integers in the range [1, N].
Example:
Input: N = 5
Output: 2
Explanation :
GCD(1, 2) : 1
GCD(1, 3) : 1
GCD(1, 4) : 1
GCD(1, 5) : 1
GCD(2, 3) : 1
GCD(2, 4) : 2
GCD(2, 5) : 1
GCD(3, 4) : 1
GCD(3, 5) : 1
GCD(4, 5) : 1
Input: N = 6
Output: 3
Explanation: GCD of pair (3, 6) is the maximum.
Naive Approach:
The simplest approach to solve the problem is to generate all possible pairs from [1, N] and calculate GCD of each pair. Finally, print the maximum GCD obtained.
Time Complexity: O(N2logN)
Auxiliary Space: O(1)
Efficient Approach:
Follow the steps below to solve the problem:
- Since all the pairs are distinct, then, for any pair {a, b} with GCD g, either of a or b is greater than g.
- Considering b to be the greater number, b > 2g, since 2g is the smallest multiple of g greater than it.
- Since b cannot exceed N, and 2g <= N.
- Therefore, g = floor(n/2).
- Therefore, the maximum GCD that can be obtained is floor(n/2), when pair chosen is (floor(n/2), 2*floor(n/2)).
Illustration:
N = 6
Maximum GCD = 6/2 = 3, occurs for the pair (3, 6)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void find( int n)
{
cout << n / 2 << endl;
}
int main()
{
int n = 5;
find(n);
return 0;
}
|
Java
class GFG{
static void find( int n)
{
System.out.println(n / 2 );
}
public static void main(String[] args)
{
int n = 5 ;
find(n);
}
}
|
Python3
def find(n):
print (n / / 2 )
if __name__ = = '__main__' :
n = 5
find(n)
|
C#
using System;
class GFG{
static void find( int n)
{
Console.Write(n / 2);
}
public static void Main( string [] args)
{
int n = 5;
find(n);
}
}
|
Javascript
<script>
function find(n)
{
document.write(parseInt(n / 2, 10) + "</br>" );
}
let n = 5;
find(n);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...