给定两个数的总和和gcd 和 .任务是找到数字a 和 b 。如果数字不存在,则打印 .
例子:
Input: sum = 6, gcd = 2
Output: a = 4, b = 2
4 + 2 = 6 and GCD(4, 2) = 2
Input: sum = 7, gcd = 2
Output: -1
There are no such numbers whose sum is 7 and GCD is 2
方法:由于给出了 GCD,因此已知这两个数字都是它的倍数。
- 选择第一个数字作为gcd然后另一个数字将是sum – gcd 。
- 如果上一步中选择的两个数字的总和等于sum,则打印这两个数字。
- 否则数字不存在并打印-1代替。
下面是上述方法的实现:
C++
// C++ program to find two numbers
// whose sum and GCD is given
#include
using namespace std;
// Function to find two numbers
// whose sum and gcd is given
void findTwoNumbers(int sum, int gcd)
{
// sum != gcd checks that both the
// numbers are positive or not
if (__gcd(gcd, sum - gcd) == gcd && sum != gcd)
cout << "a = " << min(gcd, sum - gcd)
<< ", b = " << sum - min(gcd, sum - gcd)
<< endl;
else
cout << -1 << endl;
}
// Driver code
int main()
{
int sum = 8;
int gcd = 2;
findTwoNumbers(sum, gcd);
return 0;
}
Java
// Java program to find two numbers
// whose sum and GCD is given
import java.util.*;
class Solution{
//function to find gcd of two numbers
static int __gcd(int a,int b)
{
if (b==0) return a;
return __gcd(b,a%b);
}
// Function to find two numbers
// whose sum and gcd is given
static void findTwoNumbers(int sum, int gcd)
{
// sum != gcd checks that both the
// numbers are positive or not
if (__gcd(gcd, sum - gcd) == gcd && sum != gcd)
System.out.println( "a = " + Math.min(gcd, sum - gcd)
+ ", b = " + (int)(sum - Math.min(gcd, sum - gcd)) );
else
System.out.println( -1 );
}
// Driver code
public static void main(String args[])
{
int sum = 8;
int gcd = 2;
findTwoNumbers(sum, gcd);
}
}
//contributed by Arnab Kundu
Python3
# Python 3 program to find two numbers
# whose sum and GCD is given
from math import gcd as __gcd
# Function to find two numbers
# whose sum and gcd is given
def findTwoNumbers(sum, gcd):
# sum != gcd checks that both the
# numbers are positive or not
if (__gcd(gcd, sum - gcd) == gcd and
sum != gcd):
print("a =", min(gcd, sum - gcd),
", b =", sum - min(gcd, sum - gcd))
else:
print(-1)
# Driver code
if __name__ == '__main__':
sum = 8
gcd = 2
findTwoNumbers(sum, gcd)
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to find two numbers
// whose sum and GCD is given
using System;
class GFG
{
// function to find gcd of two numbers
static int __gcd(int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
// Function to find two numbers
// whose sum and gcd is given
static void findTwoNumbers(int sum, int gcd)
{
// sum != gcd checks that both the
// numbers are positive or not
if (__gcd(gcd, sum - gcd) == gcd && sum != gcd)
Console.WriteLine("a = " + Math.Min(gcd, sum - gcd) +
", b = " + (int)(sum - Math.Min(gcd, sum - gcd)));
else
Console.WriteLine( -1 );
}
// Driver code
public static void Main()
{
int sum = 8;
int gcd = 2;
findTwoNumbers(sum, gcd);
}
}
// This code is contributed by anuj_67..
PHP
Javascript
输出:
a = 2, b = 6
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。