永夜初晗凝碧天

本博客现已全部转移到新地址,欲获取更多精彩文章,请访问http://acshiryu.github.io/

导航

poj 2115 同余方程与扩展欧几里德

C Looooops
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10606 Accepted: 2483

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
题目意思给出A,B,C,问对于C语句语句
for (variable = A; variable != B; variable += C)

statement;
循环的次数,如果是死循环,就输出FOREVER 。其中数据都在2^k内,且都为非负数
也就是说当数据大于2^k时就要对2^k取模
这题题目意思很好理解,细细观察发现假设循环执行了t次,则会有 (A + C×t )= B mod 2 ^k 题目就是要求的最小的非负数t 。
对于同余方程的解法,可以参考http://www.cnblogs.com/ACShiryu/archive/2011/08/03/2126676.html
题目数据虽然都是32位,但在中间算的时候有可能超int 故要用__int64 刚开始没注意到,WA了2次,有一次是对1左移时没强制转换。

http://www.cnblogs.com/ACShiryu

参考代码:

 1 #include<iostream>
2 #include<cstdlib>
3 #include<cstdio>
4 #include<cstring>
5 #include<algorithm>
6 #include<cmath>
7 using namespace std;
8 void gcd ( __int64 a , __int64 b , __int64 &d , __int64 &x ,__int64 &y )
9 {
10 if ( ! b )
11 d = a , x = 1 , y = 0 ;
12 else
13 gcd ( b , a % b , d , y , x ) , y -= x * ( a / b ) ;
14 }
15 int main()
16 {
17 __int64 a, b , c, k ;
18 while ( cin >> a >> b >> c >> k , a || b || c || k )
19 {
20 __int64 d , x , y ;
21 gcd ( c , ( ( __int64 ) 1 )<< k , d , x , y ) ;
22 if ( ( b - a ) % d != 0 )
23 cout << "FOREVER" <<endl;
24 else
25 {
26 __int64 ans = ( b - a ) / d * x ;
27 ans = ans % ( ( ( ( __int64 ) 1 )<< k ) / d ) ;
28 if ( ans < 0 )
29 ans += ( ( ( __int64 ) 1 )<< k ) / d ;
30 cout << ans << endl ;
31 }
32 }
33 return 0;
34 }

posted on 2011-08-09 10:10  ACShiryu  阅读(472)  评论(0编辑  收藏  举报