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


问题

使用C编程语言中的递归函数,找到给定两个数字的最大公约数(GCD)。

解决方案

使用递归函数找到给定两个数字的最大公约数(GCD)的解决方案如下:

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

算法

请参考下面给出的算法,使用递归函数找到给定两个数字的最大公约数(GCD)。

步骤1 - 定义递归函数。

步骤2 - 读取两个整数a和b。

步骤3 - 调用递归函数。

a. if i>j
b. then return the function with parameters i,j
c. if i==0
d. then return j
e. else return the function with parameters i,j%i.

流程图

下面给出了一个流程图,用于使用递归函数找到给定两个数字的最大公约数(GCD)的算法。

示例

以下是使用递归函数查找给定两个数字的最大公约数(GCD)的C程序

 在线演示

#include<stdio.h>
#include<math.h>
unsigned int GCD(unsigned i, unsigned j);
int main(){
   int a,b;
   printf("Enter the two integers: 
");    scanf("%d%d",&a,&b);    printf("GCD of %d and %d is %d
",a,b,GCD(a,b));    return 0; } /* Recursive Function*/ unsigned int GCD(unsigned i, unsigned j){    if(j>i)       return GCD(j,i);    if(j==0)       return i;    else       return GCD(j,i%j); }

输出

执行上述程序时,会产生以下结果:

Enter the two integers: 4 8
GCD of 4 and 8 is 4

更新于: 2021年8月31日

24K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告