POJ-2115-C Looooops (linear congruent equation)

link:

https://vjudge.net/problem/POJ-2115

Meaning of the questions:

A Compiler Mystery: We are 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 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 < 2 k) modulo 2 k.

Ideas:

Solution \ (A * X + C \ equiv B (MOD \, 2 ^ K) \) .
Conversion \ (C * X + 2 = K BA ^ \) .
Extended Euclidean solved.

Code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<math.h>
#include<vector>

using namespace std;
typedef long long LL;
const int INF = 1e9;

const int MAXN = 1e6+10;

LL a, b, c, k;

LL ExGcd(LL a, LL b, LL &x, LL &y)
{
    if (b == 0)
    {
        x = 1, y = 0;
        return a;
    }
    LL d = ExGcd(b, a%b, x, y);
    LL tmp = x;
    x = y;
    y = tmp - (a/b)*y;
    return d;
}


int main()
{
    while(~scanf("%lld%lld%lld%lld\n", &a, &b, &c, &k) && (a || b || c || k))
    {
        LL x, y;
        LL B = 1LL<<k;
        LL d = ExGcd(c, B, x, y);
        if ((b-a)%d != 0)
        {
            puts("FOREVER");
            continue;
        }
        x = x*(b-a)/d;
        x = (x%(B/d)+(B/d))%(B/d);
        printf("%lld\n", x);
    }

    return 0;
}

Guess you like

Origin www.cnblogs.com/YDDDD/p/11789741.html