用c语言写求最大公约数的程序
时间: 2024-06-09 19:04:29 浏览: 18
以下是使用 C 语言编写求最大公约数的程序:
```c
#include <stdio.h>
int gcd(int x, int y) {
if (y == 0) {
return x;
}
else {
return gcd(y, x % y);
}
}
int main() {
int x, y;
printf("请输入两个正整数:");
scanf("%d %d", &x, &y);
int result = gcd(x, y);
printf("%d 和 %d 的最大公约数为 %d\n", x, y, result);
return 0;
}
```
程序中使用了递归方式实现求最大公约数,即如果 `y` 等于 0,直接返回 `x`,否则返回 `y` 和 `x % y` 的最大公约数。在 `main` 函数中,获取用户输入的两个整数 `x` 和 `y`,然后调用 `gcd` 函数求它们的最大公约数并输出结果。
相关问题
用循环结构写个C语言程序求最大公约数
好的,以下是用循环结构写的C语言程序求最大公约数:
```c
#include <stdio.h>
int main() {
int a, b, temp;
printf("请输入两个整数,用空格隔开:");
scanf("%d %d", &a, &b);
// 确保a是较小的数
if (a > b) {
temp = a;
a = b;
b = temp;
}
// 求最大公约数
int i;
for (i = a; i >= 1; i--) {
if (a % i == 0 && b % i == 0) {
printf("%d和%d的最大公约数为%d\n", a, b, i);
return 0;
}
}
return 0;
}
```
希望能对你有帮助!现在请听一个笑话:一个程序员在写代码时,突然发现自己上网看小说的浏览器还在打开,于是她毅然关掉了自己的编辑器,继续看小说。
一个c语言程序求最大公约数和最小公倍数
以下是一个C程序,用于计算两个整数的最大公约数和最小公倍数:
```c
#include <stdio.h>
int main()
{
int num1, num2, i, gcd, lcm;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
// 计算最大公约数
for(i=1; i<=num1 && i<=num2; i++)
{
if(num1%i==0 && num2%i==0)
gcd = i;
}
// 计算最小公倍数
lcm = (num1*num2)/gcd;
printf("GCD of %d and %d is %d\n", num1, num2, gcd);
printf("LCM of %d and %d is %d\n", num1, num2, lcm);
return 0;
}
```
该程序首先要求用户输入两个整数。然后,它使用一个for循环来计算这两个数的最大公约数。在循环中,如果当前迭代的数字同时是num1和num2的因数,则将其存储在gcd变量中。最后,程序使用公式lcm = (num1*num2)/gcd来计算最小公倍数,并将其打印到屏幕上。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)