POJ 2115 C Looooops

来源:互联网 发布:如何当好淘宝客服? 编辑:程序博客网 时间:2024/05/20 00:16
C Looooops
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 13902 Accepted: 3467

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 163 7 2 167 3 2 163 4 2 160 0 0 0

Sample Output

0232766FOREVER

Source

CTU Open 2004
有半个多学期没有扩展欧几里德了 ,遇到这个题的时候竟然把这种方法给忽略了,看来还要在想一想过程,有点不懂为什么了,要重新该看看了。
#include <stdio.h>#include <string.h>#include <math.h>__int64 x,y;int main(){    __int64 gcd(__int64 a,__int64 b);    __int64 i,j,n,m,s,t;    __int64 A,B,C,D,k;    while(scanf("%I64d %I64d %I64d %I64d",&A,&B,&C,&k)!=EOF)    {        if(!A&&!B&&!C&&!k)        {            break;        }        for(i=1,D=1;i<=k;i++)        {            D=D*2;        }        B=((B-A)%D+D)%D;        t=gcd(C,D);        if(B%t)        {            printf("FOREVER\n"); continue;        }        D=D/t;        x=(x*(B/t)%D+D)%D;        printf("%I64d\n",x);    }    return 0;}__int64 gcd(__int64 a,__int64 b){    __int64 t,k;    if(b==0)    {        x=1; y=0;        return a;    }    k=gcd(b,a%b);    t=x;    x=y;    y=t-(a/b)*y;    return k;}