Given a sum S and product P, the task is to print any pair of integers which has the sum S and the product P. If there exists no such pair, then print -1.
Input: S = 5, P = 6
Output: 2, 3
Sum = 2 + 3 = 5, and
Product = 2 * 3 = 6
Input: S = 5, P = 9
No such pair exists
Approach: Let the pair be (x, y). Therefore, according to the problem, the given sum (S) will be (x + y) and the given product (P) will be (x * y)
If the pair is (x, y) Given that product P = x * y y = P / x; (eq.. 1) Given that sum S = x + y S = x + (P / x) from (eq..1) x2 - Sx + P = 0 which is a quadratic equation in x.
Since this is a quadratic equation, we just need to find it’s roots, using the below equation.
Here: a = 1 b = -S c = P
Therefore the above equation will be changed as:
Below is the implementation of the above approach:
3, 2 -1
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print N lines of 4 numbers such that every pair among 4 numbers has a GCD K
- Check if a given number can be expressed as pair-sum of sum of first X natural numbers
- Pair of prime numbers with a given sum and minimum absolute difference
- Check if a given pair of Numbers are Betrothed numbers or not
- Sum of series formed by difference between product and sum of N natural numbers
- Product of absolute difference of every pair in given Array
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Print any pair of integers with sum of GCD and LCM equals to N
- Print all n-digit numbers whose sum of digits equals to given sum
- Pair with min absolute difference and whose product is N+1 or N+2
- Count of pairs in a given range with sum of their product and sum equal to their concatenated number
- Sum and product of k smallest and k largest prime numbers in the array
- Sum and product of k smallest and k largest composite numbers in the array
- Print N numbers such that their product is a Perfect Cube
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Program for dot product and cross product of two vectors
- Construct an array from its pair-product
- Count of elements which is product of a pair or an element square
- Maximum possible GCD for a pair of integers with product N
- Find a pair in Array with second largest product
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.