- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 x, y, z that satisfy 2/n = 1/x + 1/y + 1/z in C++
In this problem, we are given integer values n. Our task is to find x, y, z that satisfy 2/nx + 1/y + 1/z.
Let's take an example to understand the problem,
Input : n = 4 Output : 4, 5, 20
Solution Approach
A simple solution to the problem is by finding the solution using the value of n.
If n = 1, no solution for the equation.
If n > 1, the solution to the equation is x = n, y = n+1, z = n(n+1).
The solution is $2/n\:=\:1/n\:+1\:(n+1)\:+\:1/(n^*(n\:+\:1))$
Example
Program to illustrate the working of our solution
#include <iostream> using namespace std; void findSolution(int a, int b, int n){ for (int i = 0; i * a <= n; i++) { if ((n - (i * a)) % b == 0) { cout<<i<<" and "<<(n - (i * a)) / b; return; } } cout<<"No solution"; } int main(){ int a = 2, b = 3, n = 7; cout<<"The value of x and y for the equation 'ax + by = n' is "; findSolution(a, b, n); return 0; }
Output
The value of x and y for the equation 'ax + by = n' is 2 and 1
Advertisements