c语言用递归方法求两个数的最大公约数
时间: 2024-06-16 09:07:05 浏览: 11
在C语言中,可以使用递归方法来求两个数的最大公约数。最大公约数(Greatest Common Divisor,简称GCD)是指能够同时整除两个数的最大正整数。
下面是使用递归方法求两个数的最大公约数的示例代码:
```c
#include <stdio.h>
// 递归函数,用于求两个数的最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
int main() {
int num1, num2;
printf("请输入两个整数:");
scanf("%d %d", &num1, &num2);
int result = gcd(num1, num2);
printf("最大公约数为:%d\n", result);
return 0;
}
```
在上述代码中,`gcd`函数使用递归的方式来计算最大公约数。当`b`为0时,即找到了最大公约数,返回`a`;否则,将`b`和`a`对`b`取余后的结果作为参数递归调用`gcd`函数。
相关问题
c语言用递归求两个数的最大公约数
下面是用C语言递归求两个数的最大公约数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
int MaxCommonFactor(int a, int b);
int main() {
int a,b,y;
printf("Input two positive integers,a,b:\n");
scanf("%d,%d",&a, &b);
if(a<=0 || b<=0) {
printf("Input error!");
} else {
y = MaxCommonFactor(a,b);
printf("MaxCommonFactor = %d",y);
}
return 0;
}
//计算a 与 b 的最大公约数并返回
int MaxCommonFactor(int a, int b) {
if(a == b) return a;
else if(a>b) return MaxCommonFactor(a - b, b);
else return MaxCommonFactor(a, b - a);
}
```
这个程序中,我们定义了一个函数`MaxCommonFactor`,它接受两个整数参数`a`和`b`,并返回它们的最大公约数。在函数中,我们使用递归的方式来计算最大公约数。具体来说,我们首先判断`a`和`b`是否相等,如果相等,那么它们的最大公约数就是它们本身;否则,我们就将`a`和`b`中较大的那个数减去较小的那个数,然后递归调用`MaxCommonFactor`函数,直到`a`和`b`相等为止。
递归求两个数的最大公约数c语言
以下是使用递归方法求两个数的最大公约数的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
int gcd(int n, int m);
int main() {
int n, m, t;
scanf("%d %d", &n, &m);
t = gcd(n, m);
printf("%d", t);
return 0;
}
int gcd(int n, int m) {
long s;
if (m == 0) {
s = n;
} else {
s = gcd(m, n % m);
}
return s;
}
```
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)