poj 2115 Looooops

C Looooops
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 23637   Accepted: 6528

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 < 2k) modulo 2k

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 < 2k) 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

Source



分析:
a+cx%2^k=b,求解最小的x
a-b+cx%2^k=0
cx=(b-a)%2^k·························@1:典型的同余方程,通过ext_gcd求解
cx+(2^k)y=(b-a)
当且仅当 gcd(c,2^k)|(b-a)时,方程有解。
我们通过ext_gcd求得 cx+(2^k)y=gcd(b-a)的解 x,y,gcd.
把方程的两边同时/gcd*(b-a)即得到 @1式的解。
即 x = x*(b-a)/gcd。
因为我们要求最小的x,所以我们求出符合条件的x的变化周期:T:= (2^k)/gcd.
然后通过(x%T+T)%T得到最小的x,别问我为什么,因为我也不知道为什么。
#include<iostream>
#include<stdio.h>
using namespace std;
long long pow(long long k)
{
    long long ans=1;
    for(int i=0;i<k;i++)
        ans*=2;
    return ans;
}
long long ext_gcd(long long a,long long b,long long *x,long long *y)
{
    if(b==0)
    {
        *x=1,*y=0;
        return a;
    }
    long long r = ext_gcd(b,a%b,x,y);
    long long t = *x;
    *x = *y;
    *y = t - a/b * *y;
    return r;
}
int main()
{
    long long a,b,c,k;
    while(~scanf("%I64d%I64d%I64d%I64d",&a,&b,&c,&k))
    {
        if((a+b+c+k)==0) break;
        long long x,y;
        long long _gcd_ = ext_gcd(c,pow(k),&x,&y);
        if((b-a)%_gcd_)
        {
            printf("FOREVER
");
            continue;
        }
        long long tmp_ans = x*(b-a)/_gcd_;
        long long T = pow(k)/_gcd_;/*总结一下: b/gcd是 ax+by = k*gcd中,x*k/gcd的周期*/
        long long ans = (tmp_ans%T+T)%T;
        printf("%I64d
",ans);
    }
    return 0;
}
View Code