Open In App

Maximum possible GCD for a pair of integers with product N

Given an integer N, the task is to find the maximum possible GCD among all pair of integers with product N.
Examples:

Input: N=12 
Output:
Explanation: 
All possible pairs with product 12 are {1, 12}, {2, 6}, {3, 4} 
GCD(1, 12) = 1 
GCD(2, 6) = 2 
GCD(3, 4) = 1 
Therefore, the maximum possible GCD = maximum(1, 2, 1) = 2



Input:
Output: 2
Explanation: 
All possible pairs with product 4 are {1, 4}, {2, 2} 
GCD(1, 4) = 1 
GCD(2, 2) = 2 
Hence, maximum possible GCD = maximum(1, 2) = 2

Naive Approach: 
The simplest approach to solve this problem is to generate all possible pairs with product N and calculate GCD of all such pairs. Finally, print the maximum GCD obtained. 
Time Complexity: O(NlogN) 
Auxiliary Space: O(1)
Efficient Approach: 
The above approach can be optimized by finding all divisors of the given number N. For each pair of divisors obtained, calculate their GCD. Finally, print the maximum GCD obtained.
Follow the steps below to solve the problem:



Below is the implementation of the above approach:




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return
/// the maximum GCD
int getMaxGcd(int N)
{
    int maxGcd = INT_MIN, A, B;
 
    // To find all divisors of N
    for (int i = 1; i <= sqrt(N); i++) {
 
        // If i is a factor
        if (N % i == 0) {
            // Store the pair of factors
            A = i, B = N / i;
 
            // Store the maximum GCD
            maxGcd = max(maxGcd, __gcd(A, B));
        }
    }
 
    // Return the maximum GCD
    return maxGcd;
}
 
// Driver Code
int main()
{
 
    int N = 18;
    cout << getMaxGcd(N);
 
    return 0;
}




// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
     
// Function to return
// the maximum GCD
static int getMaxGcd(int N)
{
    int maxGcd = Integer.MIN_VALUE, A, B;
     
    // To find all divisors of N
    for(int i = 1; i <= Math.sqrt(N); i++)
    {
         
        // If i is a factor
        if (N % i == 0)
        {
             
            // Store the pair of factors
            A = i;
            B = N / i;
         
            // Store the maximum GCD
            maxGcd = Math.max(maxGcd, gcd(A, B));
        }
    }
     
    // Return the maximum GCD
    return maxGcd;
}
     
// Driver Code
public static void main(String s[])
{
    int N = 18;
     
    System.out.println(getMaxGcd(N));
}
}
 
// This code is contributed by rutvik_56




# Python3 program to implement
# the above approach
import sys
import math
 
# Function to return
# the maximum GCD
def getMaxGcd(N):
     
    maxGcd = -sys.maxsize - 1
 
    # To find all divisors of N
    for i in range(1, int(math.sqrt(N)) + 1):
 
        # If i is a factor
        if (N % i == 0):
             
            # Store the pair of factors
            A = i
            B = N // i
 
            # Store the maximum GCD
            maxGcd = max(maxGcd, math.gcd(A, B))
         
    # Return the maximum GCD
    return maxGcd
 
# Driver Code
N = 18
 
print(getMaxGcd(N))
 
# This code is contributed by code_hunt




// C# program to implement
// the above approach
using System;
class GFG{
     
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
     
// Function to return
// the maximum GCD
static int getMaxGcd(int N)
{
    int maxGcd = int.MinValue, A, B;
     
    // To find all divisors of N
    for(int i = 1; i <= Math.Sqrt(N); i++)
    {
         
        // If i is a factor
        if (N % i == 0)
        {
             
            // Store the pair of factors
            A = i;
            B = N / i;
         
            // Store the maximum GCD
            maxGcd = Math.Max(maxGcd, gcd(A, B));
        }
    }
     
    // Return the maximum GCD
    return maxGcd;
}
     
// Driver Code
public static void Main(String []s)
{
    int N = 18;
     
    Console.WriteLine(getMaxGcd(N));
}
}
 
// This code is contributed by sapnasingh4991




<script>
// javascript program to implement
// the above approach
 
    function gcd(a , b)
    {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
 
    // Function to return
    // the maximum GCD
    function getMaxGcd(N)
    {
        var maxGcd = Number.MIN_VALUE, A, B;
 
        // To find all divisors of N
        for (i = 1; i <= Math.sqrt(N); i++)
        {
 
            // If i is a factor
            if (N % i == 0)
            {
 
                // Store the pair of factors
                A = i;
                B = N / i;
 
                // Store the maximum GCD
                maxGcd = Math.max(maxGcd, gcd(A, B));
            }
        }
 
        // Return the maximum GCD
        return maxGcd;
    }
 
    // Driver Code
        var N = 18;
        document.write(getMaxGcd(N));
 
// This code is contributed by aashish1995
</script>

Output
3

Time Complexity: O(?N*log(N)) 
Auxiliary Space: O(1)

Prime Factorization Approach:-

We can factorize the given number N into its prime factors. Let’s say the prime factorization of N is:

Below is the implementation of the above approach:




#include <bits/stdc++.h>
using namespace std;
 
int getMaxGcd(int N) {
    map<int, int> primeFactors;
    int temp = N;
 
    // Factorize N into its prime factors
    for (int i = 2; i <= sqrt(N); i++) {
        while (temp % i == 0) {
            primeFactors[i]++;
            temp /= i;
        }
    }
    if (temp > 1) {
        primeFactors[temp]++;
    }
 
    // Compute the maximum possible GCD
    int maxGcd = 1;
    for (auto factor : primeFactors) {
        int exponent = factor.second;
        maxGcd *= pow(factor.first, exponent / 2);
    }
 
    return maxGcd;
}
 
int main() {
    int N = 18;
    cout << getMaxGcd(N) << endl;  // Output: 3
}




import java.util.*;
 
class GFG {
    static int getMaxGcd(int N) {
        Map<Integer, Integer> primeFactors = new HashMap<>();
        int temp = N;
         
        // Factorize N into its prime factors
        for (int i = 2; i <= Math.sqrt(N); i++) {
            while (temp % i == 0) {
                primeFactors.put(i, primeFactors.getOrDefault(i, 0) + 1);
                temp /= i;
            }
        }
        if (temp > 1) {
            primeFactors.put(temp, primeFactors.getOrDefault(temp, 0) + 1);
        }
         
        // Compute the maximum possible GCD
        int maxGcd = 1;
        for (int factor : primeFactors.keySet()) {
            int exponent = primeFactors.get(factor);
            maxGcd *= Math.pow(factor, exponent / 2);
        }
         
        return maxGcd;
    }
     
    public static void main(String[] args) {
        int N = 18;
        System.out.println(getMaxGcd(N));  // Output: 3
    }
}
 
// this code is contributed by Satyamn120




#Python equivalent
import math
 
def getMaxGcd(N):
    primeFactors = {}
    temp = N
     
    # Factorize N into its prime factors
    for i in range(2, int(math.sqrt(N)) + 1):
        while temp % i == 0:
            primeFactors[i] = primeFactors.get(i, 0) + 1
            temp //= i
    if temp > 1:
        primeFactors[temp] = primeFactors.get(temp, 0) + 1
     
    # Compute the maximum possible GCD
    maxGcd = 1
    for factor in primeFactors.keys():
        exponent = primeFactors[factor]
        maxGcd *= factor ** (exponent // 2)
         
    return maxGcd
 
N = 18
print(getMaxGcd(N))  # Output: 3




using System;
using System.Collections.Generic;
 
class GFG {
    static int GetMaxGcd(int N) {
        Dictionary<int, int> primeFactors = new Dictionary<int, int>();
        int temp = N;
 
        // Factorize N into its prime factors
        for (int i = 2; i <= Math.Sqrt(N); i++) {
            while (temp % i == 0) {
                if (primeFactors.ContainsKey(i)) {
                    primeFactors[i]++;
                } else {
                    primeFactors.Add(i, 1);
                }
                temp /= i;
            }
        }
        if (temp > 1) {
            if (primeFactors.ContainsKey(temp)) {
                primeFactors[temp]++;
            } else {
                primeFactors.Add(temp, 1);
            }
        }
 
        // Compute the maximum possible GCD
        int maxGcd = 1;
        foreach (int factor in primeFactors.Keys) {
            int exponent = primeFactors[factor];
            maxGcd *= (int)Math.Pow(factor, exponent / 2);
        }
 
        return maxGcd;
    }
 
    static void Main(string[] args) {
        int N = 18;
        Console.WriteLine(GetMaxGcd(N)); // Output: 3
    }
}




function getMaxGcd(N) {
  let primeFactors = {};
  let temp = N;
   
  // Factorize N into its prime factors
  for (let i = 2; i <= Math.sqrt(N); i++) {
    while (temp % i === 0) {
      primeFactors[i] = (primeFactors[i] || 0) + 1;
      temp /= i;
    }
  }
  if (temp > 1) {
    primeFactors[temp] = (primeFactors[temp] || 0) + 1;
  }
   
  // Compute the maximum possible GCD
  let maxGcd = 1;
  for (let factor in primeFactors) {
    let exponent = primeFactors[factor];
    maxGcd *= Math.pow(factor, Math.floor(exponent / 2));
  }
   
  return maxGcd;
}
 
const N = 18;
console.log(getMaxGcd(N));

Output
3

Time complexity:- The time complexity of the given implementation is O(sqrt(N)logN) because we loop from 2 to sqrt(N) to factorize N into its prime factors, and each factorization operation takes O(log N) time due to the division operation. The loop runs for at most sqrt(N) iterations, hence the overall time complexity is O(sqrt(N)logN).

Space Complexity:-The space complexity of the implementation is O(logN) due to the use of the HashMap to store the prime factors and their exponents.

Overall, the given implementation is efficient in terms of time and space complexity, and it can handle large values of N.


Article Tags :