Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 27655 | Accepted: 7893 |
Description
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 is finished by a line containing four zeros.
Output
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,B,C,M,让计算循环次数
- 其实就是同余方程:
A + C*x = B (mod M);
- 化简下:
C*x = (B-A) (mod M);
- 无解就是forever,有解就是答案
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
typedef long long LL ;
typedef unsigned long long ULL ;
const int maxn = 1000 + 10 ;
const int inf = 0x3f3f3f3f ;
const int npos = -1 ;
const int mod = 1e9 + 7 ;
const int mxx = 100 + 5 ;
const double eps = 1e-6 ;
LL extgcd(LL a, LL b, LL &x, LL &y){
if(0==b){
x=1;
y=0;
return a;
}else{
LL r=extgcd(b,a%b,y,x);
y-=x*(a/b);
return r;
}
}
LL mod_equ(LL a, LL b, LL n){
LL x, y;
LL d=extgcd(a,n,x,y);
if(0==b%d){
x=(x%n + n)%n;
return x*(b/d)%(n/d);
}else{
return -1;
}
}
LL M, A, B, C, K, ans;
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
while(~scanf("%lld %lld %lld %lld",&A,&B,&C,&K) && (A+B+C+K)){
M=(LL)1<<K;
if(A==B){
puts("0");
}else{
ans=mod_equ(C,((B-A)%M + M)%M,M);
if(-1==ans)
puts("FOREVER");
else
printf("%lld\n",ans);
}
}
return 0;
}