//剩余数定理(韩信点兵)
#include <iostream>
int gcd(int a, int b){
if (a < b){
a = a ^ b;
b = a ^ b;
a = a ^ b;
}//交换变量
int tmp = a % b;
if (tmp == 0){
return b;
}
else{
return gcd(b, tmp);
}
}
int main(int argc, char *argv[]){
int r[3] = { 2, 1, 6 };
//int r[3] = {2, 3, 2};
//std::cin >> r[0] >> r[1] >> r[2];
int d[3] = { 3, 5, 7 };
int k[3] = { 0, 0, 0 };
int lcm = d[0] * d[1] * d[2] / gcd(d[0], gcd(d[1], d[2]));
for (int i = 0; i < 3; ++i){
for (int j = 2; j <= lcm; ++j){
std::cout << j << std::endl;
if ((j % d[i % 3] == 0)
&& (j % d[(i + 1) % 3] == 0)
&& (j % d[(i + 2) % 3] == 1)){
k[i] = j;
std::cout << "k[" << i << "]=" << k[i] << std::endl;
std::cout << "k[" << i << "]*" << r[(i + 2) % 3] << "=" << k[i] * r[(i + 2) % 3] << std::endl;
break;
}
}
}
std::cout << "ans=" << (k[0] * r[2] + k[1] * r[0] + k[2] * r[1]) % lcm << std::endl;
return 0;
}
算法竞赛入门经典 习题2-3剩余数定理+最大公约数/最小公倍数
最新推荐文章于 2021-05-16 10:10:20 发布