c语言编写程序:输入一个正整数n(1< n<2^31),对其进行质因数分解,输出分解结果>),如果输出结果中有相同的数相乘,将它们改成乘方的形式
时间: 2023-05-23 09:06:39 浏览: 180
。以下是C语言实现:
```c
#include <stdio.h>
#include <math.h>
void prime_factors(int n) {
int i, j;
int factor_count;
int factors[32];
int powers[32];
factor_count = 0;
while (n % 2 == 0) {
n /= 2;
factors[factor_count] = 2;
powers[factor_count] = 1;
factor_count++;
}
for (i = 3; i <= sqrt(n); i += 2) {
while (n % i == 0) {
n /= i;
factors[factor_count] = i;
powers[factor_count] = 1;
factor_count++;
}
}
if (n > 2) {
factors[factor_count] = n;
powers[factor_count] = 1;
factor_count++;
}
printf("%d=", n);
for (i = 0; i < factor_count; i++) {
for (j = i + 1; j < factor_count; j++) {
if (factors[j] == -1) {
continue;
}
if (factors[j] == factors[i]) {
powers[i]++;
factors[j] = -1;
}
}
if (i == factor_count - 1 || factors[i + 1] != -1) {
printf("%d", factors[i]);
if (powers[i] > 1) {
printf("^%d", powers[i]);
}
if (i != factor_count - 1) {
printf("*");
}
}
}
}
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
prime_factors(n);
return 0;
}
```
这里使用了数组来存储质因数和它们的幂,然后按格式输出。特别地,对于相同的质因数,我们将它们的幂加起来,然后输出乘方形式。
阅读全文