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

POJ-2115 C Looooops (模线性方程)

时间:2016-10-23 17:44:35      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:ted   ant   amp   exgcd   plm   ble   mina   repeat   asi   

C Looooops
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 24380   Accepted: 6793

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

 
首先列出基本方程组 A+C*x=B+(2^k)*y   →   C*x+(2^k)*y=B-A  这样就满足了 ax+by=1 的模型,所以通过扩展欧几里得求出即可。
 
 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 typedef long long LL;
 5 LL A,B,C,k;
 6 LL a,b,c,d,e,f,x,y;
 7 LL exgcd(LL a,LL b,LL &x,LL &y){
 8     if (b==0)
 9     {x=1;
10      y=0;
11      return a;
12     }
13     LL d=exgcd(b,a%b,x,y);
14     LL t=x;
15     x=y;
16     y=t-(a/b)*y;
17     return d;
18 }
19 int main(){
20     freopen ("c.in","r",stdin);
21     freopen ("c.out","w",stdout);
22     int i,j;
23     while (1)
24     {scanf("%lld%lld%lld%lld",&A,&B,&C,&k);
25      if (A==0 && B==0 && C==0 && k==0)
26       break;
27      a=C,b=1ll<<k,c=B-A;
28      d=exgcd(a,b,x,y);
29      if (c==0)
30      {puts("0");
31       continue;
32      }
33      if (c%d!=0)
34      {puts("FOREVER");
35       continue;
36      }
37      e=x*(c/d);
38      f=(e%(b/d)+b/d)%(b/d);
39      printf("%lld\n",f);
40     }
41     return 0;
42 }

 

POJ-2115 C Looooops (模线性方程)

标签:ted   ant   amp   exgcd   plm   ble   mina   repeat   asi   

原文地址:http://www.cnblogs.com/keximeiruguo/p/5990319.html

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