题目链接:poj 2115
C Looooops
Time Limit: 1000MS Memory Limit: 65536K
Description
A Compiler Mystery: We are given a C-language style for loop of type
for (variable = A; variable != B; variable += C)
statement;
I.e., a loop which starts by setting variable to value A and while variable is not equal to B, repeats statement followed by increasing the variable by C. We want to know how many times does the statement get executed for particular values of A, B and C, assuming that all arithmetics is calculated in a k-bit unsigned integer type (with values 0 <= x < 2^k) modulo 2^k.
Input
The input consists of several instances. Each instance is described by a single line with four integers A, B, C, k separated by a single space. The integer k (1 <= k <= 32) is the number of bits of the control variable of the loop and A, B, C (0 <= A, B, C < 2^k) are the parameters of the loop.
The input is finished by a line containing four zeros.
Output
The output consists of several lines corresponding to the instances on the input. The i-th line contains either the number of executions of the statement in the i-th instance (a single integer number) or the word FOREVER if the loop does not terminate.
Sample Input
3 3 2 16
3 7 2 16
7 3 2 16
3 4 2 16
0 0 0 0
Sample Output
0
2
32766
FOREVER
题意大致是给四个数A,B,C,k,问在A的基础上加多少次C可以加到B,注意到这道题的各个数是以计算机的存数模式来的,就算A一开始就大于B,也有可能加加加,加成负数最后再加回正数再加到B。分析后发现可以用扩展欧几里得解决。
解题过程:
(A + C * x) % (2 ^ k) = B,
=> A + C * x = B + (2 ^ k),
=> C * x - (2 ^ k) * y = B - A.
需要求的是加C的次数即x,带入扩展欧几里得模板即可。
在此式中B - A能整除gcd(C, 2 ^ k)时才有解,否则输出FOREVER。
另外注意这里求的是x的最小值。
相关证明戳这里:poj 2115 扩展欧几里德算法小结
(别人的博文,贴链接应该不算转载吧)
最小值有可能是负数,这道题不允许解为负数,因此要做处理。
PS:
1.这道题不用快速幂也没什么问题。
2.去掉主函数里的那些决策语句,把所有的情况都交给扩展欧几里得处理也是完全可以的。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#define MAX 100005
#define INF -0x7f7f7f7f
using namespace std;
long long multi(long long a, long long b)//这个没必要,可以直接1 << k
{
long long ret = 1;
while(b)
{
if(b & 1) ret *= a;
a *= a;
b >>= 1;
}
return ret;
}
long long exgcd(long long a, long long b, long long &x, long long &y)
{
if(!b)
{
x = 1;
y = 0;
return a;
}
long long d = exgcd(b, a % b, x, y);
long long tmp = x;
x = y;
y = tmp - a / b * y;
return d;
}
int main()
{
long long A, B, C, k, x, y;
while(~scanf("%lld %lld %lld %lld", &A, &B, &C, &k) && !(!A && !B && !C && !k))
{
k = multi(2, k);
if(A == B) printf("0\n");
else if(!C) printf("FOREVER\n");
else if(A < B && !((B - A) % C))
{
printf("%lld\n", (B - A) / C);
}
else
{
int d = exgcd(C, k, x, y);
if(!((B - A) % d))
{
x *= (B - A);
x /= d;
x = (x % (k / d) + (k / d)) % (k / d);//最小整数解,防止最后结果为负数。
printf("%lld\n", x);
}
else
printf("FOREVER\n");
}
}
return 0;
}
运行结果: