在 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