【拓展欧几里得】Looooops(求解同余方程、同余方程用法)

版权声明:侵删 [email protected] https://blog.csdn.net/weixin_43350051/article/details/86482766

                                               Looooops(点击)

 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

思路:

题目搁了两天,开始想了个很复杂的方法,花了好长时间调试结果TLE

后来实在没办法去搜了一下,才知道是用同余方程 解决

根据题目可以列出一个方程式,将加c的次数设成x:

∵   a+cx≡b(%mod);

∴  a+c*x+mod*y=b;

∴  c*x+mod*y=b-a;

根据exgcd可以求解  同时好要求出最小整数x的解就是结果

代码:

#include<stdio.h>
typedef long long LL;
LL GCD;
LL exgcd(LL a,LL b,LL &x,LL &y)  // 拓展欧几里得求x、y特解
{
    if(!b){
        x=1;y=0;return a;
    }
    GCD=exgcd(b,a%b,y,x);
    y-=a/b*x;
    return GCD;
}
LL qpow(LL c,LL  q)     // 快速幂 因为题目涉及求2^k 如果用pow可能会出错 
{
    LL ans=1;             //快速幂里面不需要%mod 和mod没有关系  不需要担心快速幂结果会超过2^k
    while(q){
        if(q%2){
            ans*=c;
        }
        c*=c;
        q/=2;
    }
    return ans;
} 
int main()
{
    LL a,b,c,k,x,y,t;
    while(scanf("%lld%lld%lld%lld",&a,&b,&c,&k)!=EOF){
        if(a==0&&b==0&&c==0&&k==0){
            break;
        }
        else{
            GCD=exgcd(c,qpow(2,k),x,y);  //将 c、mod=2^k、x、y 依次带入拓展欧几里得方程求解 
            if((b-a)%GCD){ 
                printf("FOREVER\n");   // 判断方程是否有解 
            }
            else{
                x*=((b-a)/GCD);        //类似求解ax+by=c最小整数解的方法 得出最小x的值
                t=qpow(2,k)/GCD;  //因为求x所以t=b/GCD 但这个b并不是输入的b 而是 方程里面对应
                if(t<0){              的b 即 qpow(2,k)
                    t=-t;
                }
                x=(x%t+t)%t;
                printf("%lld\n",x);      //输出结果x
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43350051/article/details/86482766
今日推荐