c++中如何把列表中每个整数分解质因数,然后将所有的质因子存储到一个集合中,最后返回这个集合
时间: 2023-05-27 16:03:35 浏览: 137
下面是一个C语言程序,可以将一个整数列表中的每个整数分解质因数,然后将所有的质因子存储到一个集合中,最后返回这个集合:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_PRIME_NUM 1000
int is_prime(int n) {
if (n <= 1) {
return 0;
}
for (int i = 2; i*i <= n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
void prime_factors(int n, int *factors, int *num_factors) {
int p = 2;
while (n > 1) {
if (n % p == 0) {
factors[(*num_factors)++] = p;
n /= p;
} else {
p++;
while (!is_prime(p)) {
p++;
}
}
}
}
void prime_set(int *nums, int len, int *prime_nums, int *num_prime_nums) {
int factors[MAX_PRIME_NUM];
int num_factors = 0;
for (int i = 0; i < len; i++) {
prime_factors(nums[i], factors, &num_factors);
}
for (int i = 0; i < num_factors; i++) {
int prime = factors[i];
int found = 0;
for (int j = 0; j < *num_prime_nums; j++) {
if (prime == prime_nums[j]) {
found = 1;
break;
}
}
if (!found) {
prime_nums[(*num_prime_nums)++] = prime;
}
}
}
int main() {
int nums[] = {12, 15, 21, 24, 28};
int num_nums = sizeof(nums) / sizeof(nums[0]);
int prime_nums[MAX_PRIME_NUM];
int num_prime_nums = 0;
prime_set(nums, num_nums, prime_nums, &num_prime_nums);
printf("Prime factors:\n");
for (int i = 0; i < num_prime_nums; i++) {
printf("%d\n", prime_nums[i]);
}
return 0;
}
```
运行结果:
```
Prime factors:
2
3
5
7
```
阅读全文