Given sum and gcd of two numbers and . The task is to find both the numbers a and b. If the numbers do not exist then print .
Input: sum = 6, gcd = 2
Output: a = 4, b = 2
4 + 2 = 6 and GCD(4, 2) = 2
Input: sum = 7, gcd = 2
There are no such numbers whose sum is 7 and GCD is 2
Approach: As GCD is given then it is known that both the numbers will be multiples of it.
- Choose the first number as gcd then the other number will be sum – gcd.
- If the sum of both the numbers chosen in the previous step equals to sum then print both the numbers.
- Else the numbers do not exist and print -1 instead.
Below is the implementation of the above approach:
# 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))
# Driver code
if __name__ == ‘__main__’:
sum = 8
gcd = 2
# This code is contributed by
a = 2, b = 6
- Given two numbers a and b find all x such that a % x = b
- Program to find LCM of two numbers
- Program to find LCM of 2 numbers without using GCD
- Find LCM of rational numbers
- Find the sum of the all amicable numbers up to N
- Find k numbers which are powers of 2 and have sum N | Set 1
- Program to find GCD or HCF of two numbers
- Find two numbers with sum and product both same as N
- To find sum of two numbers without using any operator
- Find two prime numbers with given sum
- Find XOR of numbers from the range [L, R]
- Find the sum of first N odd Fibonacci numbers
- Find max of two Rational numbers
- Program to find first N Iccanobif Numbers
- Find count of Almost Prime numbers from 1 to N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.