数论初步之扩展欧几里德

来源:互联网 发布:域名购买后备案 编辑:程序博客网 时间:2024/05/16 05:38

扩展欧几里德算法主要是用来解决二元线性方程的整数解的问题,,

运用到的主要是gcd的一些性质,把ax + by = n; 先利用:

如果n % gcd(a, b) == 0 则存在着整数解,并且是无数组;

否则,不成立,不存在着任何一组整数解使得成立,

然后再进行一定的转换就可以 利用 扩展gcd了

还是没有弄清楚他的运作步骤,但是还是把代码给记下来了,,一会在细细的研究一下下,

用扩展gcd求出来的是这样的式子  ax + by = gcd(a,b)

如果还要和你的n联系上的话,就还得让你的结果乘以  n1 = n * gcd;

这样才是你求的的结果,如果让你输出很多组解的话,那你就得清楚

x(所有) = x + b  / gcd *t;

y(所有) = y - b / gcd * t;

t呢就是所有的整数咯,很好推出来的,呵呵

代码如下:

#include <stdio.h>#include <iostream>#include <string>using namespace std;int extgcd(int a, int b, int &x, int &y){if (b == 0){x = 1;y = 0;return a;}int d = extgcd(b, a % b, x, y);int t = x;x = y;y = t - a / b * y;return d;}int main(){int N;int a, b;int x, y;cout << "Please input the two numbers : a and b" << endl;cin >> a >> b;cout << "Please input the numbers : N" << endl;cin >> N;int gcd = extgcd(a, b, x, y);if (N % gcd == 0){int n1 = N / gcd;cout << "Exsit the answer!" << endl;cout << "the x = " << x * n1 << endl;cout << "the y = " << y * n1 << endl;cout << "the _gcd = " << gcd << endl;}else{cout << "Not exist the answer!" << endl;}system("pause");return 0;}