分別用連續整數檢測、歐幾里得和分解質因數演算法求最大公約數
阿新 • • 發佈:2019-02-03
注:用時計算不準確,只是一個示範。#include <stdio.h> #include <time.h> #include <windows.h> #define _MIN(x,y) (((x)>(y))?(x):(y)) int GetGcd1(int m,int n)/* 連續整數檢測法 */ { int t; t=_MIN(m,n); while(t>0)/* 測試t的每個值 */ { if(m%t==0 && n%t==0) break; else t--; } return t; } int GetGcd2(int m,int n)/* 歐幾里得演算法 */ { int r; while((r=m%n)!=0) { m=n; n=r; r=m%n; } return n; } int GetGcd3(int m,int n)/* 分解質因數法 */ { int i,min,gcd; min = _MIN(m,n); gcd =1; for(i=2;i<=min;i++) { while(m>0 && n>0 && m%i ==0 && n%i ==0)/* 找到公因式 */ { gcd*=i; m/=i; n/=i; } } return gcd; } int main(int argc,char** argv) { int m,n,gcd; double time; clock_t start,end; printf("enter two integers:\n"); scanf("%d%d",&m,&n); start=clock(); gcd=GetGcd1(m,n); Sleep(1000); end=clock(); time=(double)(end-start)/CLOCKS_PER_SEC; printf("Great common divisor(GetGcd1):%d\n",gcd); printf("Time:%f\n",time); start=clock(); gcd=GetGcd2(m,n); Sleep(1000); end=clock(); time=(double)(end-start)/CLOCKS_PER_SEC; printf("Great common divisor(GetGcd2):%d\n",gcd); printf("Time:%f\n",time); start=clock(); gcd=GetGcd3(m,n); Sleep(1000); end=clock(); time=(double)(end-start)/CLOCKS_PER_SEC; printf("Great common divisor(GetGcd3):%d\n",gcd); printf("Time:%f\n",time); return 0; }