题目连接;
http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=2544
题目类型:
数论 - 扩展欧几里得
数据结构:
无
思路分析:
抽象出公式
( x + k * z ) % L = y
L = 65535 ( 整数的最大值 超过最大值则变为0 )
依旧运用扩展欧几里得的方法
对一次同余方程
A + C * X = B ( mod M ) 求解
证明:
略
源代码:
#include <iostream>
#include <stdio.h>
using namespace std;
typedef __int64 int64;
int64 _extend_gcd( int64 a, int64 b, int64 *x, int64 *y )
{
int64 x0,x1,x2,y0,y1,y2;
int64 r0,r1,r2,q;
if((a==0)&&(b==0)) { *x=0;*y=0; return -1; }
if((a==0)&&(b!=0)) { *x=0;*y=1; return b; }
if((a!=0)&&(b==0)) { *x=1;*y=0; return a; }
if((a!=0)&&(b!=0))
{
x0=0;x1=1;r0=a; y0=1;r1=b; r2=r0%r1;y1=0-r0/r1;x2=1;y2=y1;
if(r2==0) { x=0; *y=1; return r1; }
while((r1%r2)!=0)
{
r0=r1;r1=r2; q=r0/r1;
x2=x0-x1*q; y2=y0-y1*q;
x0=x1;x1=x2; y0=y1;y1=y2;
r2=r0%r1;
}
*x=x2; *y=y2;
return r2;
}
}
int main()
{
int64 x, y, m, n, l;
int64 a, b, c, k;
while( scanf( "%I64d%I64d%I64d%I64d", &a, &b, &c, &k ), a + b + c + k )
{
int64 tmp = c;
c = b - a;
a = tmp;
b = (int64)1 << k;
int64 rlt = _extend_gcd( a, b, & x, & y );
if( c % rlt != 0 )
{
puts( "FOREVER" );
}
else
{
int64 ret = x * c / rlt,
re2 = b / rlt;
ret = ret % re2 + re2;
printf( "%I64d\n", ret % re2 );
}
}
return 0;
}