NEFU84 五指山扩展欧几里德的应用

解析过程跟上一道很像,http://blog.csdn.net/u010682557/article/details/13612759


设要跳t次,我们列出方程  d*t-np=y-x;(这里的p是一个正整数)


然后开始利用扩展欧几里德来解,我自己写的那个不知道WA在哪里了,后来看了别人的,他们只是 求gcd的值的时候 另外写了个gcd的函数而已,而我顺便在扩展欧几里德时求出gcd的值就是错的,不知道是为什么,我先贴一下WA的代码 有高手路过 知道错哪里了求指点啊,刚开始数论没多久

这个代码一直WA//这个代码错误之处找出来了,注释过了


#include<iostream>
#include<cstdio>
#include<list>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<cmath>
#include<memory.h>
#include<set>

#define ll long long
#define LL __int64
#define eps 1e-8

//const ll INF=9999999999999;

#define M 400000100

#define inf 0xfffffff

using namespace std;

//vector<pair<int,int> > G;
//typedef pair<int,int> P;
//vector<pair<int,int>> ::iterator iter;
//
//map<ll,int>mp;
//map<ll,int>::iterator p;

//vector<int>G[30012];

ll extgcd(ll a,ll &x,ll b,ll &y)
{
	if(b==0)
	{
		x=1;
		y=0;
		return a;
	}
	ll r=extgcd(b,x,a%b,y);
	ll t=x;
	x=y;
	y=t-a/b*y;
	return r;
}

int main(void)
{
	int T;
	cin>>T;
	while(T--)
	{
		ll n,d,x,y;
		cin>>n>>d>>x>>y;
		ll dis;
		dis=(y-x+n)%n;
		ll t0,p0;
		ll gcd=extgcd(d,t0,n,p0);
		if(dis%gcd!=0)
		{
			puts("Impossible");
			continue;
		}
		t0=(t0+n)%n;
		ll t=(t0*dis/gcd+n/gcd)%(n/gcd);//自己原来错在这里了 不是对(n/gcd)进行取模就错了,唉刚开始数论 写的很不小心
		cout<<t<<endl;
	}
}

/*
3 4 0 2
9 7 0 5
11 4 3 8
15 4 3 8
27 8 5 25
31 4 29 31
13 3 6 7
13 3 4 9
13 3 4 7

*/

/*ans
2 1
2 1
4 1
5 1
16 1
16 1
9 1
6 1
1 1
*/





#include<iostream>
#include<cstdio>
#include<list>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<cmath>
#include<memory.h>
#include<set>

#define ll long long
#define LL __int64
#define eps 1e-8

//const ll INF=9999999999999;

#define M 400000100

#define inf 0xfffffff


using namespace std;


//vector<pair<int,int> > G;
//typedef pair<int,int> P;
//vector<pair<int,int>> ::iterator iter;
//
//map<ll,int>mp;
//map<ll,int>::iterator p;

//vector<int>G[30012];

ll extgcd(ll a,ll &x,ll b,ll &y)
{
	if(b==0)
	{
		x=1;
		y=0;
		return a;
	}
	ll r=extgcd(b,x,a%b,y);
	ll t=x;
	x=y;
	y=t-a/b*y;
	return r;
}

ll GCD(ll a,ll b)
{
	if(b==0)
		return a;
	return GCD(b,a%b);
}

int main(void)
{
	int T;
	cin>>T;
	while(T--)
	{
		ll n,d,x,y;
		cin>>n>>d>>x>>y;
		ll dis;
		dis=(y-x+n)%n;
		ll t0,p0;
		ll gcd=GCD(d,n);
		if(dis%gcd!=0)
		{
			puts("Impossible");
			continue;
		}
		d/=gcd;
		n/=gcd;
		extgcd(d,t0,n,p0);
		t0=(t0+n)%n;
		ll t=(t0*dis/gcd+n)%n;
		cout<<t<<endl;
	}
}






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值