多学习。

【数论】Acwing1301.C循坏——裴蜀定理(扩展欧几里得)

题解

代码

#include <iostream>
#include <cstdio>

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 -= a/b*x;
    return d;
}


int main()
{
    LL a,b,c,k;
    while(scanf("%lld%lld%lld%lld",&a,&b,&c,&k))
    {
        if(a == 0 && b == 0 && c == 0 && k == 0)
            break;
        LL o = 1; //要用LL的1来移位不然下方用(1 << 32) 1默认为int会导致进制丢失
        LL n = (o << k);
        LL x,y;
        LL gcd = exgcd(n,c,x,y);
        if((b-a) % gcd){
            puts("FOREVER");
        }
        else{
            y *= (b-a)/gcd;
            n /= gcd;
            printf("%lld\n",(y % n + n)%n);
        }
    }
    return 0;
}
posted @ 2022-04-15 10:03  czyaaa  阅读(36)  评论(0)    收藏  举报