求最大公约数的三种算法实现
2013-03-06 12:07
204 查看
#include<iostream> #include<time.h> using namespace std; /** * 程序功能:求最大公约数 * author: wwj * 2013/3/4 **/ //求两个数的较小值 int min(int a, int b) { int result = 0; if(a > b) { result = b; } else { result = a; } return result; } //算法1: 连续整数检测 int gcd1(int m, int n) { //1.求两个自然数较小值 int t = min(m,n); //2. m除以t,如果余数为0,则执行步骤3,否则执行步骤4 while(1) { if(m % t == 0) { //步骤3:n除以t,如果余数为0,返回t的值作为结果,否则,执行第4步 if( n % t == 0) { cout<<(double)clock() / CLOCKS_PER_SEC<<endl; return t; } else {//步骤4:t= t-1;转向第2步 t = t - 1; } } else { t = t - 1; } } } //算法2:欧几里德算法 int gcd2(int m, int n) { int r = m % n; while(r != 0) { m = n; n = r; r = m % n; } cout<<(double)clock() / CLOCKS_PER_SEC<<endl; return n; } //求num的质因数的个数 int decompose(int num, int p[]) { int i = 2, count = 0; while(i <= num) { while(num % i == 0) { p[count++] = i; num /= i; } i++; } return count; } //算法3: 分解质因数 int gcd3(int m, int n) { int a[100],b[100],c[100]; //1.将m分解质因数 int la = decompose(m,a); //2.将n分解质因数 int lb = decompose(n,b); //3.提取m和n中的公共质因数 int i=0, j=0, k=0; while(i < la && j < lb) { if(a[i] == b[j]) { c[k++] = a[i]; i++; j++; } else if(a[i] < b[i]){ i++; } else j++; } //4.将m和n的公共质因数相乘,乘积作为结果输出 int result = 1; for(int i = 0; i < k; i++) { result *= c[i]; } cout<<(double)clock() / CLOCKS_PER_SEC<<endl; return result; } int main() { int m,n; cout<<"请输入两个自然数:"<<endl; cin >> m >>n; cout << "m="<<m<<" n=" <<n<<endl; cout<<"使用连续整数检测算法求得最大公约数:"<<gcd1(m,n)<<endl; cout<<"使用欧几里德算法求得最大公约:"<<gcd2(m,n)<<endl; cout<<"使用分解质因数算法求得最大公约数:"<<gcd3(m,n)<<endl; system("pause"); return 0; }
相关文章推荐
- 白话经典算法系列之二 直接插入排序的三种实现
- 白话经典算法系列之二 直接插入排序的三种实现
- 白话经典算法系列之中的一个 冒泡排序的三种实现
- 白话经典算法系列之二 直接插入排序的三种实现
- Java利用 DES / 3DES / AES 这三种算法分别实现 对称加密
- java实现三种冒号算法的效率分析
- 白话经典算法系列之一 冒泡排序的三种实现
- 白话经典算法系列之二 直接插入排序的三种实现 .
- 白话经典算法系列之二 直接插入排序的三种实现
- 转载:三种实现集合求子集合算法
- 白话经典算法系列之一 冒泡排序的三种实现
- 快速排序(三种算法实现和非递归实现)
- CRC16 三种算法及c实现
- 算法之路----最大公约数和最小公倍数算法实现
- 三种进程调度算法的实现
- 白话经典算法系列之二 直接插入排序的三种实现
- 白话经典算法系列之一 冒泡排序的三种实现
- 白话经典算法系列之中的一个 冒泡排序的三种实现
- 三种方法实现PCA算法(Python)
- 白话经典算法系列之一 冒泡排序的三种实现