📌  相关文章
📜  一对总和为N的整数的最大可能GCD

📅  最后修改于: 2021-04-21 22:25:46             🧑  作者: Mango

给定一个整数N ,任务是找到一对整数的最大可能GCD ,以使它们的总和为N。

例子 :

天真的方法:
解决此问题的最简单方法是为所有总和为N的整数计算GCD,并在其中找到最大可能的GCD
时间复杂度: O(N 2 logN)
辅助空间: O(1)

高效方法:
请按照以下给出的步骤优化上述方法:

  • 迭代到√N并找到N的最大合适因数。
  • 如果N为质数,即无法获得任何因数,则打印1 ,因为所有对都是互质数。
  • 否则,打印最大可能的因素作为答案。

下面是上述方法的实现:

C++
// C++ Program to find the maximum
// possible GCD of any pair with
// sum N
#include 
using namespace std;
 
// Function to find the required
// GCD value
int maxGCD(int N)
{
    for (int i = 2; i * i <= N; i++) {
 
        // If i is a factor of N
        if (N % i == 0) {
 
            // Return the largest
            // factor possible
            return N / i;
        }
    }
 
    // If N is a prime number
    return 1;
}
 
// Driver Code
int main()
{
    int N = 33;
    cout << "Maximum Possible GCD value is : "
        << maxGCD(N) << endl;
    return 0;
}


Java
// Java program to find the maximum
// possible GCD of any pair with
// sum N
class GFG{
 
// Function to find the required
// GCD value
static int maxGCD(int N)
{
    for(int i = 2; i * i <= N; i++)
    {
 
        // If i is a factor of N
        if (N % i == 0)
        {
 
            // Return the largest
            // factor possible
            return N / i;
        }
    }
 
    // If N is a prime number
    return 1;
}
     
// Driver Code
public static void main(String[] args)
{
    int N = 33;
    System.out.println("Maximum Possible GCD " +
                       "value is : " + maxGCD(N));
}
}
 
// This code is conhtributed by rutvik_56


Python3
# Python3 program to find the maximum
# possible GCD of any pair with
# sum N
 
# Function to find the required
# GCD value
def maxGCD(N):
     
    i = 2
    while(i * i <= N):
 
        # If i is a factor of N
        if (N % i == 0):
 
            # Return the largest
            # factor possible
            return N // i
         
        i += 1
 
    # If N is a prime number
    return 1
 
# Driver Code
N = 33
 
print("Maximum Possible GCD value is : ",
       maxGCD(N))
 
# This code is contributed by code_hunt


C#
// C# program to find the maximum
// possible GCD of any pair with
// sum N
using System;
 
class GFG{
 
// Function to find the required
// GCD value
static int maxGCD(int N)
{
    for(int i = 2; i * i <= N; i++)
    {
 
        // If i is a factor of N
        if (N % i == 0)
        {
 
            // Return the largest
            // factor possible
            return N / i;
        }
    }
 
    // If N is a prime number
    return 1;
}
     
// Driver Code
public static void Main(String[] args)
{
    int N = 33;
    Console.WriteLine("Maximum Possible GCD " +
                      "value is : " + maxGCD(N));
}
}
 
// This code is contributed by Princi Singh


Javascript


输出:
Maximum Possible GCD value is : 11

时间复杂度: O(√N)
辅助空间: O(1)