POJ-2115(扩展欧几里得--模板题)

题目:

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.

思路:

乍一看以为是推公式的题,后来知道是扩展欧几里得。

先根据题意得出要解的方程:(A+Cx)%2^k=B;

可化为:(Cx)%(2^k)=B-A;

在化为:Cx%(2^k)=(B-A)%(2^k);

再化为:Cx+(2^k)*y=B-A;

即对应于求方程ax+by=n的一个整数解!直接上欧几里得模板套一下就出来了;

AC代码:

#include<cstdio>  
#include<cstring>  
#include<cstdlib>  
#include<cctype>  
#include<cmath>  
#include<iostream>  
#include<sstream>  
#include<iterator>  
#include<algorithm>  
#include<string>  
#include<vector>  
#include<set>  
#include<map>  
#include<stack>  
#include<deque>  
#include<queue>  
#include<list> 
using namespace std;
typedef long long ll;
ll A,B,C,a,b,c,k,ans;
void exgcd(ll a,ll b,ll &x,ll &y,ll &d){
	if(!b){
	    x=1,y=0,d=a;
	}
	else{
	    exgcd(b,a%b,y,x,d);
		y-=x*(a/b);
	}
}
int main(){
	while(cin>>A>>B>>C>>k){
		if(A==0&&B==0&&C==0&&k==0) break;
		a=C;
		b=1LL<<k;
		c=B-A;
		ll x,y,d;
		exgcd(a,b,x,y,d);
		if(c%d==0){
		    ans=(c/d*x%(b/d)+b/d)%(b/d);
		    cout<<ans<<endl;
    	}
	    else{
	    	puts("FOREVER");
	    }
	}
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值