1059. Prime Factors

其实没必要用链表,练习一下。测试点把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;
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值