在 C++ 中找到满足 ax + by = n 的 x 和 y
在这个问题中,给定三个整数 a、b 和 n。我们的任务是找到满足 ax + by = n 的 x 和 y。
我们举一个例子来理解这个问题
Input : a = 4, b = 1, n = 5 Output : x = 1, y = 1
解决方案方法
解决这个问题的一个简单方法是找出 0 到 n 之间满足该方程的值。我们通过使用该方程的改变形式来实现这一点。
x = (n - by)/a y = (n- ax)/b
如果我们得到一个满足该方程的值,我们将会打印该值,否则打印“无解”。
示例
演示我们的解决方案的程序
#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;
}输出
The value of x and y for the equation 'ax + by = n' is 2 and 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP