此程序从用户处获取两个正整数作为输入,并使用递归计算其GCD。
访问此页面了解如何 使用循环计算GCD。
使用递归计算两个数的GCD
#include <stdio.h>
int hcf(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
输出
Enter two positive integers: 366 60 G.C.D of 366 and 60 is 6.
在此程序中,递归调用会一直进行,直到n2的值等于0。