這題在學什麼
先令 x=0、step=1;處理一條 x mod a=b 時,反覆將 x 加 step,直到符合。
因 step 是先前模數的乘積,加 step 不會破壞已滿足的餘數條件;兩兩互質保證最多試 a 次。
合併後把 step 乘 a;最後 x 是一週期內最小非負解,若為 0 就改輸出 step 作為最小正解。
Step-by-step animation
韓信點兵・遞增合併同餘
步驟 1 / 3
第一條餘數
從 0 每次加 1,最先得到 3 mod 5=3。
x=3
step=5
- 已滿足
- mod 5 = 3
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
long long x = 0, step = 1;
for (int i = 0; i < 3; i++) {
long long a, b;
cin >> a >> b;
while (x % a != b)
x += step;
step *= a;
}
cout << (x ? x : step) << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。