使用递归查找最大公约数的 C 程序

要理解此示例,您应该具备以下 C 语言编程主题的知识:

该程序将两个正整数作为用户的输入,并使用递归计算 最大公约数。

访问此页面以了解如何 使用循环计算两个数的最大公约数

使用递归的两个数字的 最大公约数

#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