其实没必要用链表,练习一下。测试点把1也算在里面了,明明不算质数的。略坑。
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
typedef struct factor {
long prime;
int exp;
struct factor *next;/*因数未定,用链表存储*/
}*LinkList;
long NextPrime(long x,long n);
int main()
{
long x,NextFactor=2;
scanf("%ld", &x);
printf("%ld=", x); if (x == 1) printf("1");
LinkList head = (struct factor*)malloc(sizeof(struct factor));
head->next = NULL; head->prime = -1; head->exp = -1;
LinkList p = head;
while (NextFactor){
if(x%NextFactor == 0) {/*每当找到一个新的质数因数*/
LinkList t = (struct factor*)malloc(sizeof(struct factor));
t->prime = NextFactor; t->exp = 0; t->next = NULL;
p->next = t;
p = p->next;
while (x%NextFactor == 0) {
p->exp++;
x /= NextFactor;
}
}
NextFactor = NextPrime(NextFactor, x);
}
p = head->next;
while (p) {
printf("%ld", p->prime);
if (p->exp > 1)
printf("^%d", p->exp);
if (p->next) printf("*");
p = p->next;
}
return 0;
}
long NextPrime(long x,long n )
{
int IsPrime;
if (x == 2 && n>=3) return 3;
else {
for (long i = x + 2; i <= n; i+=2) {/*只检测奇数*/
IsPrime = 1;
for (long j = 3; j < sqrt(i) + 1; j+=2)
if (i%j == 0) {
IsPrime = 0; break;
}
if (IsPrime) return i;
}
}
return 0;
}