
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 with Sum and Product Both Same as N in C++
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.
#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.
Advertisements