1. 程式人生 > >新學期打卡第一天

新學期打卡第一天

Greatest Common Divisor(GCD)

歐幾里得演算法用於計算最大公約數,時數論的基礎演算法之一,這裡給出使用歐幾里得演算法求最大公約數的遞迴和非遞迴的程式,同時給出窮舉法求最大公約數的程式。

從計算時間,也就是時間複雜度來看,遞推法計算速度最快。

程式中包含條件編譯語句用於統計分析計算複雜度。

/*    計算兩個數的最大公約數三種演算法程式    */

#include<stdio.h>

//#define DEBUG

#ifdef DEBUG

int c1=0,c2=0,c3=0;

#endif

int gcd1(int,int);

int gcd2(int,int);

int gcd3(int,int);

int main(void)

{

int m=42,n=140;

printf("gcd1:%d %d result=%d\n",m,n,gcd1(m,n));

printf("gcd2:%d %d result=%d\n",m,n,gcd2(m,n));

#ifdef DEBUG

printf("c1=%d c2=%d c3=%d\n",c1,c2,c3);

#endif

return 0;

}

/*遞迴法:歐幾里得演算法,計算最大公約數*/

int gcd1(int m,int n)

{

#ifdef DEBUG

c1++;

#endif

return(m==0)?n:gcd1(n%m,m);

}

/*迭代法*(遞推法):歐幾里得演算法,計算最大公約數*/

int gcd2(int m,int n)

{

while(m>0)

{ #ifdef DEBUG

c2++;

#endif

int c=n%m;

n=m;

m=c;

}

return n;

}

/*   連續整數試探演算法,計算最大公約數  */

int gcd3(int m,int n)

{

if(m>n)

{

int temp=m;

m=n;

n=temp;

}

int t=m;

while(m%t||n%t)

{

#ifdef DEBUG

c3++

#endif

t--;

}

return t;

}