POJ 2115 C Looooops (扩展欧几里得)

来源:互联网 发布:火箭 知乎 成功率 编辑:程序博客网 时间:2024/06/10 23:31
C Looooops
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 21174 Accepted: 5753

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转换为:cx+2^ky=b-aac代码:
#include<stdio.h>#include<math.h>#include<string.h>#include<stack>#include<set>#include<queue>#include<vector>#include<iostream>#include<algorithm>#define MAXN 1010000#define LL long long#define ll __int64#define INF 0xfffffff#define mem(x) memset(x,0,sizeof(x))#define PI acos(-1)using namespace std;int gcd(int a,int b){return b?gcd(b,a%b):a;}LL powmod(LL a,LL b,LL MOD){LL ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}//headll x,y;ll exgcd(ll a,ll b){if(b==0){x=1;y=0;return a;}ll ans=exgcd(b,a%b);ll t=x;x=y;y=t-a/b*y;return ans;}int main(){ll a,b,c,k;while(scanf("%I64d%I64d%I64d%I64d",&a,&b,&c,&k)!=EOF){if(a==0&&b==0&&c==0&&k==0)break;ll num=pow(2,k+0.0);//printf("k=%I64d\n",k);ll kk=exgcd(c,num);//printf("kk=%I64d\n",kk);if((b-a)%kk)printf("FOREVER\n");else{//printf("x=%I64d\n",x);x=(b-a)/kk*x%num+num;//printf("x=%I64d\n",x);printf("%I64d\n",x%(num/kk));}}    return 0;}


0 0
原创粉丝点击