分别用连续整数检测、欧几里得和分解质因数算法求最大公约数

#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;
}
注:用时计算不准确,只是一个示范。
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值