在 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

更新時間:01-Feb-2022

553 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告