#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;
}
注:用时计算不准确,只是一个示范。
分别用连续整数检测、欧几里得和分解质因数算法求最大公约数
最新推荐文章于 2022-09-20 20:38:54 发布