POJ_2115_CLooooops_扩展欧基里德

今天困成狗,明天又要跑一千米,真*&*(&#)(&*(^&*%#%


题意:

for (variable = A; variable != B; variable += C)
对这个语句,计算它需要执行多少次,或者输出FOREVER,变量为长度为k的无符号整数



Input

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 < 2 k) are the parameters of the loop.

The input is finished by a line containing four zeros.

Output

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.


真是跪成狗,果然数学还是做的太少了。

首先列出同余方程c*x=b-a(mod 2^k)

然后跟按定义求乘法逆元一样,用扩展欧基里德解x:ex_gcd(c,mod,x,y),y无用

然后是扩展欧基里德之后对x的调整,不管等式右边的常数最终选几,x的最小调动幅度是mod / gcd(c,mod),列等式就可以看出这一点,BTW,y的最小调动幅度是c / gcd(c,mod),由于算法保证|x|+|y|最小,所以只需要调整一次就可以,然后我调整的时候第一次没取模就WA了也是醉


代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
long long ex_gcd(long long m,long long n,long long& x,long long& y){
	if(!n){
		x=1;
		y=0;
		return m;
	}
	int ret=ex_gcd(n,m%n,x,y);
	int tem=x;
	x=y;
	y=tem-m/n*y;
	return ret;
}
long long a,b,c,k;
int main(){
	while(scanf("%lld%lld%lld%lld",&a,&b,&c,&k)!=EOF){
		if(!a&&!b&&!c&&!k)	break;
		if(!c){
			if(a==b)	puts("0");
			else	puts("FOREVER");
			continue;
		}
		long long mod=(1LL<<k);
		long long x,n;
		long long tem=ex_gcd(c,mod,x,n);
		long long d=(b-a+mod)%mod;
		if(d%tem){
			puts("FOREVER");
			continue;
		}
		x=x*(d/tem);
		x=(x%(mod/tem)+mod/tem)%(mod/tem);
		printf("%lld\n",x);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值