c语言 输入两个整数,求它们的最大公约数
时间: 2023-06-02 10:04:08 浏览: 77
您好!我可以回答您的问题。如下是C语言代码实现:
```
#include <stdio.h>
int main()
{
int num1, num2, i, gcd;
printf("请输入两个整数:\n");
scanf("%d %d", &num1, &num2);
for(i = 1; i <= num1 && i <= num2; ++i)
{
if(num1 % i==0 && num2 % i==0)
gcd = i;
}
printf("%d 和 %d 的最大公约数为 %d\n", num1, num2, gcd);
return 0;
}
```
请注意,在您的问题中没有涉及必须回答 “抱歉,我无法回答这个问题”,所以我会根据要求尽我的最大努力来回答您的问题。如果您有其他关于编程的问题,请随时问我!
相关问题
C语言输入两个整数求最大公约数
好的,以下是 C 语言的代码实现:
```
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
int main() {
int a, b;
printf("请输入两个整数:");
scanf("%d %d", &a, &b);
int result = gcd(a, b);
printf("它们的最大公约数为:%d", result);
return 0;
}
```
其中,gcd 函数为求最大公约数的函数,main 函数中通过 scanf 获取用户输入的两个整数,然后调用 gcd 函数求它们的最大公约数,并输出结果。这样,您就可以使用 C 语言来解决您的问题了。
C语言输入两个整数求最大公约数和最小公倍数
下面是两种方法实现C语言输入两个整数求最大公约数和最小公倍数:
1. 代码实现(代码中利用辗转相除法求最大公约数):
```c
#include <stdio.h>
//辗转相除法求最大公约数
int gcd(int x, int y) {
int c = 1;
while (c > 0) {
c = x % y;
x = y;
y = c;
}
return x;
}
int main() {
int a = 0;
int b = 0;
scanf("%d%d", &a, &b);
int n = gcd(a, b);//n为a和b的最大公约数
printf("%d\n", n);
//求a和b的最小公倍数
int min = a * b / n;//min即为a和b的最小公倍数
printf("%d\n", min);
return 0;
}
```
2. 利用穷举法求最大公约数和最小公倍数:
```c
#include <stdio.h>
int main() {
int a = 0;
int b = 0;
scanf("%d%d", &a, &b);
int max = a > b ? a : b;//找到两数中的最大值
int min = a < b ? a : b;//找到两数中的最小值
int i = 0;
for (i = min; i > 0; i--) {
if (max % i == 0 && min % i == 0) {
printf("%d\n", i);//i即为a和b的最大公约数
break;
}
}
printf("%d\n", a * b / i);//a和b的最小公倍数
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](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)