码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 2115 C Looooops (线性同余方程)

时间:2015-04-22 09:44:21      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:poj

C Looooops
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 19141   Accepted: 5049

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
设步数为x,原式可以变成:A+C*x==B (mod M) -->C*x+M*y=B-A  (M为2的k次幂) 
进一步变换成:a*x + b*y =c.  (a=C,b=M,c=B-A),
解线性同余方程,方程无解则是FOREVER 

#include <stdio.h>
#include <string.h>
#include <math.h>
typedef __int64 ll;

void Exgcd(ll a,ll b,ll &d,ll &x,ll &y){
	if(b==0){
		x=1;y=0;d=a;return ;
	}
	Exgcd(b,a%b,d,y,x);
	y-=(a/b)*x;
}

int main()
{
	ll a,b,c,d,g,k,x,y;
	while(scanf("%I64d%I64d%I64d%I64d",&a,&b,&c,&k)!=EOF){
		if(a+b+c+k==0) break;
		ll temp=c;
		c=b-a;
		a=temp;
		b=(ll)pow(2,k);
		Exgcd(a,b,g,x,y);
		if(c%g){
			printf("FOREVER\n");
			continue;
		}
		x=((x*c/g)%(b/g)+(b/g))%(b/g);
		printf("%I64d\n",x);
	}
	return 0;
}


POJ 2115 C Looooops (线性同余方程)

标签:poj

原文地址:http://blog.csdn.net/u013068502/article/details/45176825

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!