본문 바로가기

IT/C

Euclide & non Euclide gcd algorithm C source

Euclide & non Euclide gcd algorithm

시간 측정 포함

------------------------------------

#include <time.h>
#include <stdio.h>

int gcd1(int m, int n);
int gcd2(int m, int n);

main(void)
{
int m;
int n;
int i;
int result;


double start, finish;


printf("m과 n을 입력하시오(always m>n) : ");
scanf("%d %d", &m, &n);

start = clock();
result = gcd1(m,n);
for(i=0; i<=999999; i++)
finish =clock();
printf("Euclid's result : %d \n", result);
printf("Execution times : %f\n",(finish-start) / (double)CLOCKS_PER_SEC );


start = clock();
result = gcd2(m,n);
for(i=0; i<=999999; i++)
finish =clock();
printf("Euclid's result : %d \n", result);
printf("Execution times : %f\n",(finish-start) / (double)CLOCKS_PER_SEC );

}

int gcd1(int m, int n)//Euclid
{
int r;
int temp;

if(m <n)
{
temp = m;
m = n;
n = temp;
}

while(m%n != 0)
{
r = m % n;
m = n;
n = r;
}

return n;
}

int gcd2(int m, int n)//non
{
int i;
int result=1;

for(i=1; i<=n; i++)
{
if(m%i==0 && n%i==0)
{
result = i;
}
}

return result;
}

file.c