C++ program to find two numbers with sum and product both same as N

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find two numbers (say ‘a’ and ‘b’) such that both

a+b = N and a*b = N are satisfied.

Eliminating ‘a’ from both the equations, we get a quadratic equation in ‘b’ and ‘N’ i.e

b2 - bN + N = 0

This equation will have two roots which will give us the value of both ‘a’ and ‘b’. Using the determinant method to find the roots, we get the value of ‘a’ and ‘b’ as,

$a= (N-\sqrt{N*N-4N)}/2\ b= (N+\sqrt{N*N-4N)}/2 $


 Live Demo

#include <iostream>
//header file for the square root function
#include <math.h>
using namespace std;
int main() {
   float N = 12,a,b;
   cin >> N;
   //using determinant method to find roots
   a = (N + sqrt(N*N - 4*N))/2;
   b = (N - sqrt(N*N - 4*N))/2;
   cout << "The two integers are :" << endl;
   cout << "a - " << a << endl;
   cout << "b - " << b << endl;
   return 0;


The two integers are :
a - 10.899
b - 1.10102
Updated on 03-Oct-2019 11:00:48