给定两个数字A和B ,任务是找到通过将数字X添加到A和B可以获得的最大公约数(GCD) 。
例子
Input: A = 1, B = 5
Output: 4
Explanation: Adding X = 15, the obtained numbers are A = 16 and B = 20. Therefore, GCD of A, B is 4.
Input: A = 2, B = 23
Output: 21
方法:这个问题可以使用欧几里得 GCD 算法的特性以非常优化的方式解决。请按照以下步骤解决问题:
- 如果 a > b: GCD(a, b)= GCD(a – b, b) 。因此, GCD(a, b) = GCD(a – b, b )。
- 将x添加到A, B,gcd(a + x, b + x) = gcd(a – b, b + x)。可以看出(a-b)保持不变。
- 可以肯定地说,这些数字的 GCD 永远不会超过(a – b) 。因为(b + x)可以通过添加一个可能的x值成为(a – b)的倍数。
- 因此,可以得出结论,GCD 仍然存在(a-b)。
下面是上述方法的实现。
C++
// C++ implementation of above approach.
#include
using namespace std;
// Function to calculate maximum
// gcd of two numbers possible by
// adding same value to both a and b
void maxGcd(int a, int b)
{
cout << abs(a - b);
}
// Driver Code
int main()
{
// Given Input
int a = 2231;
int b = 343;
maxGcd(a, b);
return 0;
}
Java
// Java implementation of above approach.
import java.io.*;
class GFG
{
// Function to calculate maximum
// gcd of two numbers possible by
// adding same value to both a and b
static void maxGcd(int a, int b)
{
System.out.println(Math.abs(a - b));
}
// Driver Code
public static void main (String[] args)
{
// Given Input
int a = 2231;
int b = 343;
maxGcd(a, b);
}
}
// This code is contributed by Potta Lokesh
Python3
# Python3 program for the above approach
# Function to calculate maximum
# gcd of two numbers possible by
# adding same value to both a and b
def maxGcd(a, b):
print(abs(a - b))
# Driver code
# Given Input
a = 2231
b = 343
maxGcd(a, b)
# This code is contributed by Parth Manchanda
C#
// C# program for the above approach
using System;
class GFG{
// Function to calculate maximum
// gcd of two numbers possible by
// adding same value to both a and b
static void maxGcd(int a, int b)
{
Console.Write(Math.Abs(a - b));
}
// Driver Code
static public void Main ()
{
// Given Input
int a = 2231;
int b = 343;
maxGcd(a, b);
}
}
// This code is contributed by code_hunt.
Javascript
输出:
1888
时间复杂度: O(1)
辅助空间: O(1)