poj 2115 C Looooops 线性同余方程

  输入 A , B, C, k

  设 D = 2^k

  则存在 ( x, y ) 使

      A + C*x = B ( mod D )

  =>   A + C*x = B + D*y

  =>     C*x - D*y = B - A

  令 a = C, b = D, c = B-A

  则转换成线性同余方程 :

    a * x + b * y = c 

  使用扩展欧基里德求解即可

解题代码

View Code
#include<stdio.h>
typedef long long LL;

LL ExGcd( LL a, LL b, LL &x, LL &y )
{
    if( b == 0 ){ x=1;y=0;return a;}
    LL d = ExGcd(b, a%b, x, y);
    LL t = x; x = y; y = t-a/b*y;
    return d;
}
LL Gcd( LL a, LL b )
{    return b == 0 ? a : Gcd( b, a%b ); }
int main()
{
    LL A, B, C, D, k;
    while( scanf("%lld%lld%lld%lld", &A,&B,&C,&k) , A+B+C+k )
    {
        D = (1LL)<<k;
        LL x, y;
        LL a = C, b = D, c = B-A;
        LL d = Gcd( a, b );
        if( c%d != 0 ) puts("FOREVER");
        else
        {
            a /= d; b /= d; c /= d;
            ExGcd( a, b, x, y );
            x =((x*c)%b+b)%b;    
            printf("%lld\n", x); 
        }    
    }
    return 0;
}
原文地址:https://www.cnblogs.com/yefeng1627/p/2842978.html