最大公约数的求法代码用c语言输出
时间: 2024-06-12 17:11:22 浏览: 5
最大公约数可以使用多种方法求解,其中辗转相除法和欧几里得算法是比较常用的两种方法。以下是两种方法的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 temp;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
int main() {
int a, b;
printf("请输入两个整数:\n");
scanf("%d %d", &a, &b);
printf("%d和%d的最大公约数为:%d\n", a, b, gcd(a, b));
return 0;
}
```
代码解释:
1. 定义了一个名为`gcd`的函数,该函数接受两个整数参数`a`和`b`,返回它们的最大公约数。
2. 在`gcd`函数中,使用while循环来实现辗转相除法,直到`b`为0时结束循环,此时`a`即为最大公约数。
3. 在`main`函数中,通过`scanf`函数获取用户输入的两个整数`a`和`b`,并调用`gcd`函数求它们的最大公约数,最后输出结果。
用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);
}
}
```
当然也可以使用非递归方式实现辗转相除法求最大公约数。
相关推荐
![](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)