c语言计算参数a和b两个数的最大公约数
时间: 2023-09-20 08:11:49 浏览: 59
以下是使用辗转相除法计算参数a和b的最大公约数的C语言代码:
```c
#include <stdio.h>
int gcd(int a, int b) {
int remainder;
while (b != 0) {
remainder = a % b;
a = b;
b = remainder;
}
return a;
}
int main() {
int a, b;
printf("请输入两个整数:\n");
scanf("%d %d", &a, &b);
printf("最大公约数为:%d\n", gcd(a, b));
return 0;
}
```
首先,定义了一个名为gcd的函数,该函数接受两个整数参数a和b,并返回它们的最大公约数。在函数体内,使用while循环和辗转相除法来计算最大公约数,并将结果存储在变量a中。最后,该函数返回a作为计算结果。
在main函数中,首先提示用户输入两个整数,然后通过scanf函数读取这两个整数。接下来,调用gcd函数计算它们的最大公约数,并将结果打印到控制台上。
相关问题
c语言用递归方法求两个数的最大公约数
在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`相等为止。