ในปัญหานี้ เราได้รับค่าจำนวนเต็มสามค่า 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
ถ้าได้ค่าที่ทำให้สมการเป็นจริง ให้พิมพ์ค่าเหล่านั้น มิฉะนั้นพิมพ์ "no solution exists"
ตัวอย่างโค้ด
#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