c语言短除法求最大公约数的算法复杂度,两个求最大公约数C/C++算法实现

#include

#include

#include

using namespace std;

//求最大公约数 LCD(Largest Common Division)

//短除法

//m=8251, n=6105;

int LCD_ShortDiv(int m, int n) {

int i, time;

int f = 1; //相同因子的乘积

for(time=0; time<100000000; time++) {

for(i=2; i<=m&&i<=n; ) {

while(m%i==0&&n%i==0) {

f*=i; //将该因子与 前面的因子相乘

m/=i;

n/=i;

}

i++;

}

}

return f;

}

//辗转相除法(欧几里得算法)

int LCD_EucAlgorithm(int m, int n) {

int i, f, time;

for(time=0; time<100000000; time++) {

i = m % n; //取余数

while(i) {

m = n; //将小的n替换成m

n = i; //将余数i替换成n

i = m % n; //再次取余,直到i=0

}

//return n; //把最后除数返回

}

return n; //把最后除数返回

}

int main() {

int m=8251, n=6105;

int f1, f2;

clock_t start, finish;

double duration1, duration2;

start= clock();

f1 = LCD_ShortDiv(m, n);

finish=clock();

duration1=(double)(finish-start)/CLOCKS_PER_SEC;

//printf("time=%lf seconds\n",duration);

//printf("result=%d\n",f1);

cout << "LCD_ShortDiv用的时间为:"<< duration1 <

cout << "最大公约数为:"<< f1 <

start = clock();

f2 = LCD_EucAlgorithm(m, n);

finish = clock();

duration2 = (double)(finish-start) / CLOCKS_PER_SEC;

cout << "LCD_EucAlgorithm用的时间为:"<< duration2 <

cout << "最大公约数为:"<< f2 << endl << endl;

cout << "相差倍数:" << duration1 / duration2;

return 0;

}

证明过程如下:

想成分苹果

d62c5b70cdc973404bc81d6a210a490f.png

一个例题:

bd059e6e28f86786ac23df9b56e4b2b9.png

做题方法:

f8678d6bf1e3a99af0bffe614101075b.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值