计算整形数组a中相邻两个元素的最大公约数,最小公倍数,其中最大公约数存入数组b中,最小公倍数存入数组c中,C语言,如何写,不用函数封装的形式写,要完整,用3种方法
时间: 2023-11-01 15:07:36 浏览: 137
方法一:
```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[] = {6, 9, 12, 15, 18};
int n = 5;
int b[n - 1], c[n - 1];
for (int i = 0; i < n - 1; i++) {
b[i] = gcd(a[i], a[i + 1]);
c[i] = lcm(a[i], a[i + 1]);
}
for (int i = 0; i < n - 1; i++) {
printf("%d ", b[i]);
}
printf("\n");
for (int i = 0; i < n - 1; i++) {
printf("%d ", c[i]);
}
printf("\n");
return 0;
}
```
方法二:
```c
#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int main() {
int a[] = {6, 9, 12, 15, 18};
int n = 5;
int b[n - 1], c[n - 1];
for (int i = 0; i < n - 1; i++) {
b[i] = gcd(a[i], a[i + 1]);
c[i] = lcm(a[i], a[i + 1]);
}
for (int i = 0; i < n - 1; i++) {
printf("%d ", b[i]);
}
printf("\n");
for (int i = 0; i < n - 1; i++) {
printf("%d ", c[i]);
}
printf("\n");
return 0;
}
```
方法三:
```c
#include <stdio.h>
int gcd(int a, int b) {
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int main() {
int a[] = {6, 9, 12, 15, 18};
int n = 5;
int b[n - 1], c[n - 1];
for (int i = 0; i < n - 1; i++) {
b[i] = gcd(a[i], a[i + 1]);
c[i] = lcm(a[i], a[i + 1]);
}
for (int i = 0; i < n - 1; i++) {
printf("%d ", b[i]);
}
printf("\n");
for (int i = 0; i < n - 1; i++) {
printf("%d ", c[i]);
}
printf("\n");
return 0;
}
```
阅读全文