AcWing1301. C循环
C循环
解题思路:
这一题和那个五指山那题本质是一样的。
我们只需要搞懂\(k\)位系统是什么意思
就是说在二进制的情况下,保留多少位数
而就是在十进制里面对每个数都需要对\(2^k\)取模
逗号表达式只有最后有值
y总代码
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL exgcd(LL a, LL b, LL &x, LL &y)
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
LL d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
int main()
{
LL a, b, c, k;
while (cin >> a >> b >> c >> k, a || b || c || k)
{
LL x, y;
LL z = 1ll << k;
LL d = exgcd(c, z, x, y);
if ((b - a) % d) cout << "FOREVER" << endl;
else
{
x *= (b - a) / d;
z /= d;
cout << (x % z + z) % z << endl;
}
}
return 0;
}
学数论的时候一定要清楚每一步是干嘛的
自己的代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long LL;
LL exgcd(LL a, LL b, LL &x, LL &y)
{
if(!b){x = 1, y = 0; return a;}
LL d = exgcd(b, a % b, y, x);
y = y - a / b * x;
return d;
}
int main()
{
LL a, b, c, k;
while(cin >> a >> b >> c >> k && a + b + c + k) // 逗号表达式只有最后的值有用
{
LL x, y; // 所有数只保留最后k位
LL z = 1ll << k; // int如果是有符号的话,最多存储的是10^9,也就是2^31-1
LL gcd = exgcd(c, z, x, y);
if((b - a) % gcd != 0) cout << "FOREVER" << endl;
else
{
x = x * (b - a) / gcd; // 我们求的是x和y
LL t = z / gcd;
//printf("%lld\n", (x % t + t) % t);
cout << ((x % t + t) % t) << endl;
}
}
return 0;
}
有什么问题可以加qq:1281372141进行交流