Find two numbers with sum and product both same as N in C++ Program


In this tutorial, we are going to write a program to find two numbers where x + y = n and x * y = n. Sometimes it's not possible to find those types of numbers. We'll print None if there are no such numbers. Let's get started.

The given numbers are the sum and products of a quadratic equation. So the number doesn't exist if n2 - 4*n<0.Else the numbers will be $$\lgroup n + \sqrt n^{2} - 4*n\rgroup/2$$ and $$\lgroup n - \sqrt n^{2} - 4*n\rgroup/2$$.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findTwoNumbersWithSameSumAndProduc(double n) {
   double imaginaryValue = n * n - 4.0 * n;
   // checking for imaginary roots
   if (imaginaryValue < 0) {
      cout << "None";
      return;
   }
   // printing the x and y
   cout << (n + sqrt(imaginaryValue)) / 2.0 << endl;
   cout << (n - sqrt(imaginaryValue)) / 2.0 << endl;
}
int main() {
   double n = 50;
   findTwoNumbersWithSameSumAndProduc(n);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

48.9792
1.02084

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 29-Dec-2020

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements