📜  查找最大GCD对为2到N范围内的整数

📅  最后修改于: 2021-04-26 19:12:41             🧑  作者: Mango

给定数字N ,任务是找到最大GCD在[2,N]范围内的一对整数。
例子:

方法:
请按照以下步骤解决问题:

  1. 如果N是偶数,则返回对{N,N / 2}
  1. 如果N为奇数,则返回对{N – 1,(N – 1)/ 2}
  1. 下面是上述方法的实现:
C++
// C++ Program to find a pair of
// integers less than or equal
// to N such that their GCD
// is maximum
#include 
using namespace std;
 
// Function to find the required
// pair whose GCD is maximum
void solve(int N)
{
    // If N is even
    if (N % 2 == 0) {
 
        cout << N / 2 << " "
             << N << endl;
    }
    // If N is odd
    else {
        cout << (N - 1) / 2 << " "
             << (N - 1) << endl;
    }
}
 
// Driver Code
int main()
{
    int N = 10;
    solve(N);
    return 0;
}


Java
// Java program to find a pair of
// integers less than or equal
// to N such that their GCD
// is maximum
 
class GFG{
 
// Function to find the required
// pair whose GCD is maximum
static void solve(int N)
{
     
    // If N is even
    if (N % 2 == 0)
    {
        System.out.print(N / 2 + " " +
                         N + "\n");
    }
     
    // If N is odd
    else
    {
        System.out.print((N - 1) / 2 + " " +
                         (N - 1) + "\n");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 10;
     
    solve(N);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 Program to find a pair 
# of integers less than or equal
# to N such that their GCD
# is maximum
 
# Function to find the required
# pair whose GCD is maximum
def solve(N):
     
    # If N is even
    if (N % 2 == 0):
        print(N // 2, N)
         
    # If N is odd
    else :
        print((N - 1) // 2, (N - 1))
     
# Driver Code
N = 10
solve(N)
 
# This code is contributed by divyamohan123


C#
// C# program to find a pair of
// integers less than or equal
// to N such that their GCD
// is maximum
using System;
class GFG{
 
// Function to find the required
// pair whose GCD is maximum
static void solve(int N)
{
     
    // If N is even
    if (N % 2 == 0)
    {
        Console.Write(N / 2 + " " +
                      N + "\n");
    }
     
    // If N is odd
    else
    {
        Console.Write((N - 1) / 2 + " " +
                      (N - 1) + "\n");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 10;
     
    solve(N);
}
}
 
// This code is contributed by shivanisinghss2110


Javascript


输出:
5 10
  1. 时间复杂度: O(1)
    辅助空间: O(1)