求a,b的最大公约数,用C语言输出
时间: 2024-02-19 17:02:38 浏览: 26
好的,可以使用C语言编写一个求a,b最大公约数的函数,函数如下:
```c
#include <stdio.h>
int gcd(int a, int b) {
if (a < b) { // 如果a<b,则交换a和b
int temp = a;
a = b;
b = temp;
}
int r = a % b;
while (r != 0) {
a = b;
b = r;
r = a % b;
}
return b;
}
int main() {
int a = 12, b = 18;
int result = gcd(a, b);
printf("a和b的最大公约数是:%d", result);
return 0;
}
```
在上面的代码中,我们定义了一个求a,b最大公约数的函数`gcd`,并在`main`函数中调用该函数来输出最大公约数。您可以将a和b的值修改为您需要的值,然后运行该程序即可得到结果。
相关问题
最大公约数的求法代码用c语言输出
最大公约数可以使用多种方法求解,其中辗转相除法和欧几里得算法是比较常用的两种方法。以下是两种方法的C语言代码实现:
辗转相除法:
```
#include <stdio.h>
int MaxCommonFactor(int a, int b){
int c;
if(a<=0 || b<=0) return -1; //判断输入是否合法
while(b!=0){ //余数不为0,继续相除,直到余数为0;
c=a%b;
a=b;
b=c;
}
return a;
}
int main(void){
int a,b;
scanf("%d,%d",&a,&b);
printf("%d\n",MaxCommonFactor(a,b));
return 0;
}
```
欧几里得算法:
```
#include <stdio.h>
int MaxCommonFactor(int a, int b){
if(a<=0 || b<=0) return -1; //判断输入是否合法
if(b==0) return a;
return MaxCommonFactor(b, a%b); //递归调用
}
int main(void){
int a,b;
scanf("%d,%d",&a,&b);
printf("%d\n",MaxCommonFactor(a,b));
return 0;
}
```
用C语言输出,用辗转相除法求最大公约数
好的,这个问题属于技术问题,可以直接回答。
用C语言可以通过递归实现辗转相除法求最大公约数,代码如下:
```c
#include <stdio.h>
int gcd(int a, int b);
int main() {
int a, b, result;
printf("请输入两个数:\n");
scanf("%d %d", &a, &b);
result = gcd(a, b);
printf("%d和%d的最大公约数是:%d\n", a, b, result);
return 0;
}
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
```
当然也可以使用非递归方式实现辗转相除法求最大公约数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)