基于c语言求两个数最大公约数调用函数
时间: 2024-06-14 20:03:54 浏览: 12
```c
#include<stdio.h>
int fun(int x, int y) {
int i, t;
if(x < y) {
t = x;
x = y;
y = t;
}
while(y != 0) {
i = x % y;
x = y;
y = i;
}
return x;
}
int main() {
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", fun(a, b));
return 0;
}
```
相关问题
C语言调用函数求两个数的最大公约数
可以使用C语言中的函数来求两个数的最大公约数。C语言中有多种方法可以实现求最大公约数的函数,以下是其中一种方法的示例代码:
```c
#include <stdio.h>
// 函数声明
int gcd(int m, int n);
int main() {
int m = 0;
int n = 0;
printf("请输入两个整数: ");
scanf("%d %d", &m, &n);
int result = gcd(m, n); // 调用函数求最大公约数
printf("最大公约数为:%d\n", result);
return 0;
}
// 函数定义
int gcd(int m, int n) {
int tmp = 0;
while (tmp = m % n) {
m = n;
n = tmp;
}
return n;
}
```
其中,`gcd`函数使用的是辗转相除法来求最大公约数。在`main`函数中,先输入两个整数,然后调用`gcd`函数求最大公约数,最后输出结果。
c语言求三个数最大公约数
在C语言中,可以使用欧几里得算法(辗转相除法)来求解三个数的最大公约数。欧几里得算法的基本思想是通过不断用较小数去除较大数,然后用除数去除余数,直到余数为0为止,此时除数即为最大公约数。
以下是使用C语言实现求三个数最大公约数的代码示例:
```c
#include <stdio.h>
// 求两个数的最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// 求三个数的最大公约数
int gcdOfThree(int a, int b, int c) {
return gcd(gcd(a, b), c);
}
int main() {
int a, b, c;
printf("请输入三个整数:");
scanf("%d %d %d", &a, &b, &c);
int result = gcdOfThree(a, b, c);
printf("三个数的最大公约数为:%d\n", result);
return 0;
}
```
请注意,以上代码中使用了递归来实现求两个数的最大公约数,并在此基础上求解三个数的最大公约数。在主函数中,首先通过`scanf`函数获取用户输入的三个整数,然后调用`gcdOfThree`函数求解最大公约数,并将结果打印输出。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)