给定一个数字N ,任务是在[2, N]范围内找到一对具有最大 GCD 的整数。
例子:
Input: N = 10
Output: 5
Explaination:
Maximum possible GCD between all possible pairs is 5 which occurs for the pair (10, 5).
Input: N = 13
Output: 6
Explaination:
Maximum possible GCD between all possible pairs is 6 which occurs for the pair (12, 6).
方法:
请按照以下步骤解决问题:
- 如果N是偶数,则返回对{N, N / 2} 。
Illustration:
If N = 10, Maximum possible GCD for any pair is 5( for the pair {5, 10}).
If N = 20, Maximum possible GCD for any pair is 10( for the pair {20, 10}).
- 如果N是奇数,则返回{N – 1, (N – 1) / 2} 对。
Illustration:
If N = 11, Maximum possible GCD for any pair is 5( for the pair {5, 10}).
If N = 21, Maximum possible GCD for any pair is 10( for the pair {20, 10}).
- 下面是上述方法的实现:
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
- 时间复杂度: O(1)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live