求最大公约数辗转相除c
时间: 2023-12-12 09:34:24 浏览: 18
以下是使用辗转相除法求最大公约数的C语言代码实现:
```c
#include <stdio.h>
int main() {
int x, y;
scanf("%d%d", &x, &y);
while (1) {
if (x < y) { // 比较大小,让小的数放在后面
int tmp = x;
x = y;
y = tmp;
}
if (x % y == 0) { // 若余数为 0 则 y 为两数的最大公约数;
printf("最大公约数的 %d\n", y);
break;
} else { // 若余数不为 0,则令 x = y,y = 余数,重复循环
int tmp = x % y;
x = y;
y = tmp;
}
}
return 0;
}
```
相关问题
c语言求最大公约数辗转相除法
好的,我来给您介绍一下使用 C 语言实现求最大公约数辗转相除法的方法。
辗转相除法,也叫欧几里得算法,是求两个数的最大公约数的一种方法。其基本思想是:用较大的数除以较小的数,再用余数去除较小的数,如此反复,直到余数为零时,最后的除数就是这两个数的最大公约数。
下面是使用 C 语言实现求最大公约数辗转相除法的代码示例:
```c
#include <stdio.h>
int main()
{
int a, b, c;
printf("请输入两个整数:");
scanf("%d%d", &a, &b);
while (b != 0)
{
c = a % b;
a = b;
b = c;
}
printf("它们的最大公约数为:%d\n", a);
return 0;
}
```
以上代码中,我们先从用户输入两个整数,然后在 while 循环中使用辗转相除法求出它们的最大公约数,最后输出结果。
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("请输入两个数:");
scanf("%d %d", &a, &b);
int result = gcd(a, b);
printf("最大公约数为:%d\n", result);
return 0;
}
```
在这个代码中,我们定义了一个 `gcd` 函数,这个函数接收两个整数参数 `a` 和 `b`,并使用辗转相除法求出它们的最大公约数。然后在 `main` 函数中,我们从用户输入读取两个数,调用 `gcd` 函数求出它们的最大公约数,并输出结果。
相关推荐
![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)