C Looooops
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 18799 |
|
Accepted: 4924 |
Description
A Compiler mystery:we is 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 are not equal to B, repeats statement followed By increasing the variable by C. We want to know what many times does the statement get executed for particular values of A, B and C, assuming this all Arit Hmetics 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 are described by a A, a and four integers a, B, C and K separated by a single space. The integer k (1 <= k <=) is the number of bits of the control variable of the loop and A, B, C (0 <= A, B, c < 2k) is 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
Source
CTU Open 2004
Analysis:
Extended Euclid:
For ax+by=c, the minimum integer solution is calculated
D=GCD (A, B)
1. Seek the x0,y0 of Ax0+by0=d first. Then both sides multiply D get a (X0*C/D) +b (Y0*C/D) =GCD (A, b) *c/d=c, find out X=X0*C/D,Y=Y0*C/D
2. Find the minimum solution: The maximum solution x, the minimum solution = (x (b/d) +b/d)% (b/d)
Reference Learning Website: http://www.cnblogs.com/comeon4mydream/archive/2011/07/18/2109060.html
1#include <cstdio>2#include <algorithm>3#include <iostream>4#include <string>5#include <cstring>6#include <vector>7 using namespacestd;8typedefLong Longll;9ll EXGCD (ll a,ll b,ll &x,ll &y) {//extended Euclidean algorithmTen if(b==0){ Onex=1; Ay=0; - returnA; - } thell D=EXGCD (b,a%b,x,y); -ll t=y; -y=x-a/b*y; -x=T; + returnD; - } + intMain () { A ll A, B, C, K; at while(cin>>a>>b>>c>>k&& (a| | b| | B|]k)) { -ll b=1ll<<k,x,y; -ll C=b-a,a=C; -ll d=EXGCD (a,b,x,y); - if(c%d) { -cout<<"FOREVER"<<Endl; in } - Else{ tob=b/d;//If this step is less, the final result may not be the smallest integer solution, but a particular solution. You can think about why B is divided by D . + //cout<<d<<endl; -cout<< ((x*c/d%b+b)%b) <<endl;//finding the smallest integer solution the } * } $ return 0;Panax Notoginseng}
POJ 2115 C Looooops