数论初步之欧几里德

来源:互联网 发布:php 重定向 url 编辑:程序博客网 时间:2024/06/05 07:42

这里一定要注意,还有一种情况,当然这中情况以前没有接触到,

就是任何数和0的最大公约数,应该是那个数本身的,原因就是,0除以任何数都可以整除.

任何一个数都是零的约数,张见识了,

原来gcd应该是那样写的

忘了还是要再加一个点就是gcd的时间复杂度O(ln n^3 );

看下面的代码:

#include <stdio.h>#include <string.h>#include <iostream>#include <string>using namespace std;/*辗转相除法-即欧几里德算法*/ int gcd(int a, int b){//return a % b == 0 ? b : gcd(b, a % b);//晕死了,,这是错误的,这样是处理不了 b == 0的. return b == 0 ? a : gcd(b, a % b); }int main(){int a, b;cout << "Input the two numbers : " << endl;while (cin >> a >> b){int ans = gcd(a,b);cout << "_gcd(a, b) : " << ans << endl;cout << "_lcm(a, b) : " <<  a / ans * b << endl;cout << "Input the two numbers : " << endl;}system("pause");return 0;}


原创粉丝点击