upc 【数论】C Looooops(拓展欧几里得)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/winter2121/article/details/82025361

【数论】C Looooops

时间限制: 1 Sec  内存限制: 128 MB
提交: 8  解决: 4
[提交] [状态] [讨论版] [命题人:admin]

题目描述

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 < 2k) modulo 2k. 

输入

The input consists of several instances. Each instance is described by a single line with four integers A, B, C, k separated by a single space. The integer k (1 <= k <= 32) is the number of bits of the control variable of the loop and A, B, C (0 <= A, B, C < 2k) are the parameters of the loop. 

The input is finished by a line containing four zeros. 

输出

The output consists of several lines corresponding to the instances on the input. The i-th line contains either the number of executions of the statement in the i-th instance (a single integer number) or the word FOREVER if the loop does not terminate. 

样例输入

3 3 2 16
3 7 2 16
7 3 2 16
3 4 2 16
0 0 0 0

样例输出

0
2
32766
FOREVER

[提交][状态]

【题意】

在mod 2^k 范围内,(a+xc)%(2^k) = b  即(a+xc)= y(2^k) + b   (x,y均为未知整数)

整理得:xc - y(2^k) = b-a   非常符合拓展欧几里得形式 ax+by=gcd(a,b)

当b-a是gcd(c,2^k))时,有解。

若有解,则利用拓展欧几里得得出特解x0,然后x0要乘上(b-a)/gcd(c,2^k)

令t= (2^k)/gcd(c,2^k);

通解x=x0+ k *t,明显当x大于t时,都可以再让k减1,因此最小正整数解x就是x%t

我的误区:求解过程中我纠结于    为什么不是x0先%t再乘(b-a)/gcd(c,2^k)。  原因:先%再乘得不到最小解,但是可以先%再乘,然后再%t一次。我又有了疑问,最后一次为什么%的是t,等式右边已经不是gcd,而是b-a?原因是x每加t,都存在可行的y使得等式右边等于gcd,因此也能使右边等于gcd的倍数。

【代码】

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

ll gcd(ll a,ll b){while(b)b^=a^=b^=a%=b;return a;}
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,y,x);
    y-=a/b*x;
    return d;
}

int main()
{
    ll a,b,c,k,ans=0;
    while(cin>>a>>b>>c>>k,a||b||c||k)
    {
        ans=0;
        ll x,y,d=exgcd(c,1ll<<k,x,y);
        if((b-a)%d)ans=-1;
        ll t=(1ll<<k)/d;
        x*=(b-a)/d;
        x=(x%t+t)%t;
        if(ans==0)cout<<x<<endl;
        else puts("FOREVER");
    }
}

猜你喜欢

转载自blog.csdn.net/winter2121/article/details/82025361
UPC