
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- Find GCD of two numbers
- Java Program to Find GCD of two Numbers
- Program to find GCD or HCF of two numbers in C++
- C++ program to find two numbers from two arrays whose sum is not present in both arrays
- GCD and LCM of two numbers in Java
- C++ code to find three numbers whose sum is n
- Program to find product of few numbers whose sum is given in Python
- Find the GCD of N Fibonacci Numbers with given Indices in C++
- C program to find sum and difference of two numbers
- Take two numbers m and n & return two numbers whose sum is n and product m in JavaScript
- Find any pair with given GCD and LCM in C++
- Print all n-digit numbers whose sum of digits equals to given sum in C++
- Count of n digit numbers whose sum of digits equals to given sum in C++
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm
- Find out the GCD of two numbers using while loop in C language
Advertisements