思路:
1:让输入的数(i)从第一个素数(j)除,能除净,记录j。若不能到第三步
2: i = i / j;;继续第一步
3: 将下一个素数赋值给j;继续第一步
上面那个错误是当输入1时不能正确输出,改了一下
#include <stdio.h>
#include <stdlib.h>
#define YES 1
#define NO 0
typedef struct prime_factor{
long int factor; //储存素数因子
int num; //有几个
struct prime_factor *next;
}prime_factor;
int is_prime(long int i){ //判断是否为素数
long int j;
for(j = 2; j <= i / 2; ++j)
if(i / j == 0)
return NO;
return YES;
}
int main(){
struct prime_factor *head, *q, *p;
head = malloc(sizeof(prime_factor));
head->next = NULL;
q = head;
long int N;
scanf("%ld", &N);
long int i = N;
long int j = 2;
while(i != 1){ //商不为1,继续
if(is_prime(j) == YES){ //若为素数
if(i % j == 0){
p = malloc(sizeof(prime_factor));
p->factor = j;
p->next = NULL;
++(p->num);
q->next = p;
q = p;
i /= j;
while(i % j == 0 && i != 0){ //看这个素数能被除几次
++p->num;
i /= j;
}
}
++j;
}
}
//print
p = head->next;
printf("%ld=", N);
if(N == 1)
printf("1");
else{
while(p != NULL){ //因为上面用的是尾插,直接输出
printf("%ld", p->factor);
if(p->num > 1){
printf("^%d", p->num);
}
if(p->next != NULL)
printf("*");
p = p->next;
}
}
}