C Looooops POJ - 2115 (exgcd)

一个编译器之谜:我们被给了一段C++语言风格的循环 
for(int i=A;i!=B;i+=C)

内容;

其中所有数都是k位二进制数,即所有数时膜2^k意义下的。我们的目标时球出 内容 被执行了多少次。 

Input

输入包含若干组。每组被描述为一个单身的行有四个正整数 A, B, C, k 被一个单身的空格分开。输入以0 0 0 0结束。1 <= k <= 32, 0 <= A, B, C < 2  k

Output

输出包含若干行表示每组数据的答案,若该循环不会停止则输出一行"FOREVER"(不包含引号)。 

Sample Input

1 3 2 4
1 5 2 4
1 2 4 3
0 0 0 0

Sample Output

1
2
FOREVER

这和青蛙的那个题是一样的 想象成跑圈
写出式子 就可以了
注意最后对x的处理
ax + by = c
最后 b /= d;
x = (x % b + b) % b;
输出x即可

#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <map>
#include <cctype>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <bitset>
#define rap(i, a, n) for(int i=a; i<=n; i++)
#define rep(i, a, n) for(int i=a; i<n; i++)
#define lap(i, a, n) for(int i=n; i>=a; i--)
#define lep(i, a, n) for(int i=n; i>a; i--)
#define rd(a) scanf("%d", &a)
#define rlld(a) scanf("%lld", &a)
#define rc(a) scanf("%c", &a)
#define rs(a) scanf("%s", a)
#define rb(a) scanf("%lf", &a)
#define rf(a) scanf("%f", &a)
#define pd(a) printf("%d\n", a)
#define plld(a) printf("%lld\n", a)
#define pc(a) printf("%c\n", a)
#define ps(a) printf("%s\n", a)
#define MOD 2018
#define LL long long
#define ULL unsigned long long
#define Pair pair<int, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define _  ios_base::sync_with_stdio(0),cin.tie(0)
//freopen("1.txt", "r", stdin);
using namespace std;
const int maxn = 10010, INF = 0x7fffffff;

LL gcd(LL a, LL b)
{
    return b == 0 ? a : gcd(b, a % b);
}

LL exgcd(LL a, LL b, LL& d, LL& x, LL& y)
{
    if(!b)
    {
        d = a;
        x = 1;
        y = 0;
    }
    else
    {
        exgcd(b, a % b, d, y, x);
        y -= x * (a / b);
    }
}


int main()
{
    LL a, b, c, k, x, y, d;
    while(cin >> a >> b >> c >> k)
    {
        if(a == 0 && b == 0 && c == 0 && k == 0)
            break;
        LL s = 1LL << k;
        if((b - a) % gcd(c, s))
        {
            cout << "FOREVER" << endl;
            continue;
        }
        exgcd(c, s, d, x, y);
        s /= d;
        x *= (b - a) / d;
        x = (x % s + s) % s;
        cout << x << endl;
    }


    return 0;
}

猜你喜欢

转载自www.cnblogs.com/WTSRUVF/p/10283874.html