poj 2115 C Looooops 数论

来源:互联网 发布:g76螺纹编程第一刀 编辑:程序博客网 时间:2024/05/07 20:50

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 163 7 2 167 3 2 163 4 2 160 0 0 0

Sample Output

0232766FOREVER
#include<stdio.h>#include<string.h>__int64 extend_gcd(__int64 a,__int64 b,__int64& x,__int64& y){    if(b==0)    {        x=1;        y=0;        return a;    }    __int64 d=extend_gcd(b,a%b,x,y);    __int64 xt=x;    x=y;    y=xt-a/b*y;    return d;}int main(void){    __int64 A,B,C,k;    __int64 a,b,n,x,y,d;    while(scanf("%I64d %I64d %I64d %I64d",&A,&B,&C,&k))    {        if(!A && !B && !C && !k)            break;         a=C;         b=B-A;        n=(__int64)1<<k;         d=extend_gcd(a,n,x,y);        if(b%d!=0)            printf("FOREVER\n");        else        {            x=(x*(b/d))%n;            x=(x%(n/d)+n/d)%(n/d);            printf("%I64d\n",x);        }    }    return 0;}

x=[ (B-A+2^k)%2^k ]/C

C*X=(B-A+2^k)%2^k

一开始 方程不知道咋办 后来 看到别人统一一下变量 顿时 愚蠢的我感觉清晰了一点点 

令a=C, b=B-A, MOD=2^k;

方程变成了 ax=(n+MOD)%MOD;

看到某个大神贴的一张图片很给力 我也贴一下,顺便贴一下他的解析过程,很容易懂得,一开始学数论 不可能自己完全推出来 都是要看要做,做多了应该就行了把,我天赋比较差的,求保佑:!


该方程有解的充要条件为 gcd(a,n) | b ,即 b% gcd(a,n)==0

令d=gcd(a,n)

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

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

那么原题就是要计算b% gcd(a,n)是否为0,若为0则计算最小整数解,否则输出FOREVER

 

当有解时,关键在于计算最大公约数 d=gcd(a,n) 与 最小解x0

参考《算法导论》,引入欧几里得扩展方程  d=ax+by ,

通过EXTENDED_EUCLID算法(P571)求得d、x、y值,其中返回的x就是最小解x0,求d的原理是辗转相除法(欧几里德算法)

再利用MODULAR-LINEAR-EQUATION-SOLVER算法(P564)通过x0计算x值。注意x0可能为负,因此要先 + n/d 再模n/d。





0 0
原创粉丝点击