exgcd
D - C Looooops
http://acm.sdut.edu.cn:8080/vjudge/contest/view.action?cid=212#problem/D
#include <stdio.h> #include<iostream> using namespace std; long long exgcd(long long a,long long b,long long &x,long long &y) { if(b==0) { x=1; y=0; return a; } long long d; long long t; d=exgcd(b,a%b,x,y); t=x; x=y; y=t-a/b*y; return d; } int main() { long long A,B,C,k; while(scanf("%lld %lld %lld %lld",&A,&B,&C,&k)) { if(A == 0 && B==0 && C==0 &&k==0) break; long long a=C; long long b=B-A; long long n=(long long)1<<k; long long x,y; long long d; d=exgcd(a,n,x,y); if(b%d!=0) printf("FOREVER\n"); else { x=(x*(b/d))%n; x=(x%(n/d)+n/d)%(n/d); printf("%lld\n",x); } } return 0; }