C语言两个整数最大公约数
时间: 2024-06-13 09:06:24 浏览: 19
以下是两种C语言求两个整数最大公约数的方法:
1.辗转相除法
```c
#include <stdio.h>
int main() {
int a, b;
int c = 0;
printf("请输入两个整数:");
scanf("%d %d", &a, &b);
c = (a > b) ? b : a; //三目运算符 将最小的赋给c
while (a % c != 0 || b % c != 0) {
c--;
}
printf("最大公约数为:%d\n", c);
return 0;
}
```
2.更相减损法
```c
#include <stdio.h>
int main() {
int a, b, c;
printf("请输入两个整数:");
scanf("%d%d", &a, &b);
c = a % b;
while (c != 0) {
a = b;
b = c;
c = a % b;
}
printf("最大公约数为:%d", b);
return 0;
}
```
相关问题
c语言两个整数最大公约数
可以使用辗转相除法求两个整数的最大公约数,具体步骤如下:
1. 用较大数除以较小数,得到余数
2. 如果余数为0,则较小数即为最大公约数
3. 如果余数不为0,则用较小数除以余数,再得到余数
4. 重复上述步骤,直到余数为0,此时上一次的除数即为最大公约数
下面是用C语言实现这个算法的代码:
```c
#include <stdio.h>
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1, num2, result;
printf("请输入两个整数:");
scanf("%d %d", &num1, &num2);
result = gcd(num1, num2);
printf("%d和%d的最大公约数是:%d\n", num1, num2, result);
return 0;
}
```
输入两个整数后,程序会输出它们的最大公约数。
c语言两个整数的最大公约数
以下是两种C语言求两个整数最大公约数的方法:
1.辗转相除法
```c
#include <stdio.h>
int main() {
int a, b;
int c = 0;
printf("请输入两个整数:");
scanf("%d %d", &a, &b);
c = (a > b) ? b : a; //三目运算符 将最小的赋给c
while (a % c != 0 || b % c != 0) {
c--;
}
printf("最大公约数为:%d\n", c);
return 0;
}
```
2.更相减损法
```c
#include <stdio.h>
int main() {
int a, b, c;
printf("请输入两个整数:");
scanf("%d%d", &a, &b);
c = a % b;
while (c != 0) {
a = b;
b = c;
c = a % b;
}
printf("最大公约数为:%d", b);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)