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

[poj 2115] C Looooops 扩展欧几里得

2016-03-31 20:42 393 查看
C Looooops

Time Limit: 1000MS Memory Limit: 65536K

Total Submissions: 21706 Accepted: 5927

Description

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 < 2k) modulo 2k.

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 < 2k) 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

Source

CTU Open 2004

题目链接

http://poj.org/problem?id=2115

题意:对于C的for(i=A ; i!=B ;i +=C)循环语句,问在k位存储系统中循环几次才会结束。

若在有限次内结束,则输出循环次数。

否则输出死循环。

思路

———————-(A+C*x)=B(mod n)———————;

即 Cx=(B-A)(mod 2^k)

=C

b=B-A

n=2^k

–》ax=b (mod n)

!!所以方程 a*x+b*y=n;我们可以先用扩展欧几里德算法求出一组x0,y0。也就是a*x0+b*y0=(a,b);然后两边同时除以(a,b),再乘以n。这样就得到了方程a*x0*n/(a,b)+b*y0*n/(a,b)=n;我们也就找到了方程的一个解。!!

ax-ny=b 有解的充要条件为 gcd(a,n) | b ,即 b% gcd(a,n)==0

有该方程的 最小整数解为 x = e (mod n/d)

其中e = [x0 mod(n/d) + n/d] mod (n/d) ,x0为方程的最小解

代码

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
long long  A,B,C,k;
long long a,b;
long long x,y;

long long  ex_gcd(long long  a,long long  b,long long & x,long long  &y)
{

if(b==0)
{
x=1;
y=0;
return a;
}
long long d= ex_gcd(b,a%b,x,y);
int t=x;
x=y;
y=t-a/b*y;
return d;
}
int main()
{
while(scanf("%lld %lld %lld %lld",&A,&B,&C,&k))
{
if(!A&&!B&&!C&&!k) return 0;
a=C;
b=B-A;
long long n=(long long )1<<k;
long long d;
d=ex_gcd(a,n,x,y);

if(b==0)
{
printf("0\n");
continue;
}

if(b%d==0)
{
x=(x*(b/d))%n;
x=(x%(n/d)+n/d)%(n/d);
printf("%lld\n",x);
}
else  printf("FOREVER\n");

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: