您的位置:首页 > 运维架构

【POJ - 2115 】 Looooops 【扩展欧几里得 求不定方程】

2017-10-29 22:18 459 查看
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

题意 ,让求这个 (A+x*C)%(2^k)=B 转化一下,

A + C * y = B + x * ( 1 < < k ) ⇒ C*y - x *(1 < < k)= B - A .

有什么发现没有? 不定方程? bingo ,之后都很简单了 。

#include<stdio.h>
#define  LL long long

const int MAXN = 1e5;
const int MAXM = 1e6;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;
LL exgcd(LL a,LL b,LL &d,LL &x,LL &y ){
if(!b) { d=a ; x= 1 ,y = 0;}
else {
exgcd(b,a%b,d,y,x);
y-=a/b*x;
}
}

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 m=(1LL<<k);
LL d,x0,y0;
exgcd(c,m,d,x0,y0);
if((b-a)%d)  puts("FOREVER");
else {
LL y=(b-a)/d*x0;
m/=d;
printf("%lld\n",(y%m+m)%m);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: