- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find two numbers whose sum and GCD are given in C++
We have the sum and gcd of two numbers a and b. We have to find both numbers a and b. If that is not possible, return -1. Suppose the sum is 6 and gcd is 2, then the numbers are 4 and 2.
The approach is like, as the GCD is given, then it is known that the numbers will be multiples of it. Now there following steps
If we choose the first number as GCD, then the second one will be sum − GCD
If the sum of the numbers is chosen in the previous step is the same as the sum, then print both numbers.
Otherwise print -1, as a number does not exist.
Example
#include <iostream> #include <algorithm> using namespace std; void printTwoNumbers(int s, int g) { if (__gcd(g, s - g) == g && s != g) cout << "first number = " << min(g, s - g) << "\nsecond number = " << s - min(g, s - g) << endl; else cout << -1 << endl; } int main() { int sum = 6; int gcd = 2; printTwoNumbers(sum, gcd); }
Output
first number = 2 second number = 4
- Related Articles
- Find GCD of two numbers
- Find two numbers whose product is $-24$ and sum is 2.
- Find two numbers whose sum is 27 and product is 182.
- Find two consecutive whole numbers whose sum is 19.
- Program to find GCD or HCF of two numbers in C++
- Find the GCD of N Fibonacci Numbers with given Indices in C++
- Find two consecutive numbers whose squares have the sum 85.
- C++ program to find two numbers from two arrays whose sum is not present in both arrays
- Swift Program to Find GCD of two Numbers
- Java Program to Find GCD of two Numbers
- Kotlin Program to Find GCD of two Numbers
- GCD and LCM of two numbers in Java
- Program to find product of few numbers whose sum is given in Python
- Find out the GCD of two numbers using while loop in C language
- Find any pair with given GCD and LCM in C++

Advertisements