代码
#include <stdio.h>
int GCD(int x,int y);
int main(){
int a,b;
printf("Please enter two natural numbers :\n");
scanf("%d%d",&a,&b);// get two natural numbers
// print out the greatest common divisor
printf("The greatest common divisor of two natural numbers are:%d\n",GCD(a,b));
}
int GCD(int x,int y){
int temp;
if(x < y){// make x >= y
temp = x;
x = y;
y = temp;
}
if(y == 0)// use recursion to find GCD
return x;
else if(y > 0)
GCD(y,x%y);
}
代码详解
The main idea is using recursion to execute the divide and take remainder step.
Next step is to find
base step:
if(y == 0) return x;
recursive step:
else if(y > 0) GCD(y,x%y);