C语言使用递归求最大公约数的程序

要理解这个示例,您应该了解以下 C 编程 主题


此程序从用户处获取两个正整数作为输入,并使用递归计算其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。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战