Maximum possible GCD for a pair of integers with sum N
Given an integer N, the task is to find the maximum possible GCD of a pair of integers such that their sum is N.
Examples :
Input: N = 30
Output: 15
Explanation: GCD of (15, 15) is 15, which is the maximum possible GCD
Input: N = 33
Output: 11
Explanation: GCD of (11, 22) is 11, which is the maximum possible GCD
Naive Approach:
The simplest approach to solve this problem is to calculate GCD for all pair of integers with sum N and find the maximum possible GCD among them.
Time complexity: O(N2logN)
Auxiliary Space: O(1)
Efficient Approach:
Follow the steps given below to optimize the above approach:
- Iterate up to ?N and find the largest proper factor of N.
- If N is prime, i.e. no factor could be obtained, print 1, as all pairs are co-prime.
- Otherwise, print the largest possible factor as the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxGCD( int N)
{
for ( int i = 2; i * i <= N; i++) {
if (N % i == 0) {
return N / i;
}
}
return 1;
}
int main()
{
int N = 33;
cout << "Maximum Possible GCD value is : "
<< maxGCD(N) << endl;
return 0;
}
|
Java
import java.io.*;
public class GFG{
static int maxGCD( int N)
{
for ( int i = 2 ; i * i <= N; i++)
{
if (N % i == 0 )
{
return N / i;
}
}
return 1 ;
}
public static void main(String[] args)
{
int N = 33 ;
System.out.println( "Maximum Possible GCD " +
"value is : " + maxGCD(N));
}
}
|
Python3
def maxGCD(N):
i = 2
while (i * i < = N):
if (N % i = = 0 ):
return N / / i
i + = 1
return 1
N = 33
print ( "Maximum Possible GCD value is : " ,
maxGCD(N))
|
C#
using System;
class GFG{
static int maxGCD( int N)
{
for ( int i = 2; i * i <= N; i++)
{
if (N % i == 0)
{
return N / i;
}
}
return 1;
}
public static void Main(String[] args)
{
int N = 33;
Console.WriteLine( "Maximum Possible GCD " +
"value is : " + maxGCD(N));
}
}
|
Javascript
<script>
function maxGCD(N)
{
for ( var i = 2; i * i <= N; i++)
{
if (N % i == 0)
{
return N / i;
}
}
return 1;
}
var N = 33;
document.write( "Maximum Possible GCD " +
"value is :" + maxGCD(N));
</script>
|
Output:
Maximum Possible GCD value is : 11
Time Complexity: O(?N)
Auxiliary Space: O(1)
Last Updated :
16 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...