您的位置:首页 > 其它

扩展欧几里德求不定方程 hdoj 2669

2016-05-21 10:16 330 查看

扩展欧几里德求不定方程 hdoj 2669

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=2669

题目思路:赤裸裸的求不定方程 p = m * x - n * y;

涉及到扩展欧几里德求不定方程的性质:

对于不定整数方程pa+qb=c,若 c mod Gcd(a, b)=0,则该方程存在整数解,否则不存在p , q整数解。 可以想到,因为c == 1,只有gcd(n,m) == 1,才有解。

根据扩展欧几里德算法,所得到的p,q为其中一个解(且最小),而其他整数解满足:

p = p0 + b/Gcd(p, q) * t

q = q0 - a/Gcd(p, q) * t(其中t为任意整数)

然而这题还有一个细节,x要非负数,所以你懂的,往上加b/Gcd(p, q),直到满足。

若没有接触过扩展欧几里德,可以点击:

/article/8247663.html

ac代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <map>
#include <string>
using namespace std;

int exgcd(int a,int b,int& x,int& y)
{
if(b == 0)
{
x = 1;y = 0;
return a;
}
int d = exgcd(b,a%b,x,y);
int temp = x;
x = y;
y = temp - a/b*y;
return d;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
int x,y;
int ans = exgcd(n,m,x,y);
if(ans == 1)
{
while(x<0)
{
x += m;
y -= n;
}
printf("%d %d\n",x,y);
}
else
printf("sorry\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: