poj_2115-C Looooops

来源:互联网 发布:仿真软件培训 编辑:程序博客网 时间:2024/05/19 19:42

这里写图片描述

大概意思是:给你一个数A,若A不等于B则加C,如果超过B则mod 2^k,问你要多少次才能等于B。若不能等于B则输出“FOREVER”.

题解;

设x是循环次数,y是2^k被整除(A+xC)的值
由题意得:
(A+xC)mod 2^k=B
(A+xC)-y*2^k=B
Cx=(B-A)(mod 2^k)
得出线性同余方程,然后用扩展欧几里德算法求出最小值x即为答案。
不知道的点:扩展欧几里德算法

代码:

#include <stdio.h>      #include <iostream>      #include <algorithm>      #include <sstream>      #include <stdlib.h>      #include <string.h>      #include <limits.h>      #include <string>      #include <time.h>      #include <math.h>      #include <queue>      #include <stack>      #include <map>   using namespace std;typedef long long ll;void gcd(ll a,ll b,ll& d,ll& x,ll& y){    if(!b){        d=a; x=1; y=0;    }else{        gcd(b,a%b,d,y,x);        y=y-x*(a/b);    }}int main(){    ll a,b,c,k;    while (~scanf("%lld%lld%lld%lld",&a,&b,&c,&k)&&(a||b||c||k)){        ll m=1ll<<k;        ll d,x,y;        gcd(c,m,d,x,y);        ll e=b-a;        if(e%d!=0){            printf("FOREVER\n");        }else{            x=(x*(e/d))%m;             x=(x%(m/d)+m/d)%(m/d);            printf("%lld\n",x);        }    }    return 0;}
原创粉丝点击