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

【数论】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");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雪的期许

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值