ในปัญหานี้ เราได้รับค่าจำนวนเต็มสามค่า a, b และ n หน้าที่ของเราคือ ค้นหา x และ y ที่พอใจ ax + by =n
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหา
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