
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 X and Y Satisfying Ax + By = N in C++
In this problem, we are given three integer values a, b, and n. Our task is to find x and y satisfying ax + by = n.
Let's take an example to understand the problem
Input : a = 4, b = 1, n = 5 Output : x = 1, y = 1
Solution Approach
A simple solution to the problem is by finding the value between 0 to n that satisfies the equation. We will do this by using altered forms of the equation.
x = (n - by)/a y = (n- ax)/b
If we get a value satisfying the equation, we will print the values otherwise print "no solution exists".
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