c语言输入5个整数,求最小公倍。
时间: 2024-01-22 19:17:28 浏览: 26
可以通过先求出这5个整数的最小公约数,再利用最小公约数求出最小公倍数。
最小公约数可以通过辗转相除法求得,即不断用较小的数去除较大的数,直到两数相等为止,最后的余数就是最小公约数。
代码实现如下:
```c
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int main() {
int a[5];
for (int i = 0; i < 5; i++) {
printf("请输入第%d个整数:", i + 1);
scanf("%d", &a[i]);
}
int result = a[0];
for (int i = 1; i < 5; i++) {
result = lcm(result, a[i]);
}
printf("这5个整数的最小公倍数是:%d\n", result);
return 0;
}
```
输入5个整数后,程序会依次计算出这5个数的最小公倍数并输出。
相关问题
c语言输入两个整数求乘积
您好!可以使用以下C语言代码实现输入两个整数并求乘积:
```
#include <stdio.h>
int main()
{
int num1, num2, product;
printf("请输入两个整数:\n");
scanf("%d %d", &num1, &num2);
product = num1 * num2;
printf("它们的乘积是:%d\n", product);
return 0;
}
```
其中,`scanf`函数用于从标准输入(键盘)获取用户输入的两个整数,`printf`函数用于将乘积输出到屏幕上。
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;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)