使用递归函数查找数字的最大公约数的C程序
问题
使用C编程语言中的递归函数,找到给定两个数字的最大公约数(GCD)。
解决方案
使用递归函数找到给定两个数字的最大公约数(GCD)的解决方案如下:
算法
请参考下面给出的算法,使用递归函数找到给定两个数字的最大公约数(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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP