1059. Prime Factors (25)

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1* p2^k2 *…*pm^km.

Input Specification:

Each input file contains one test case which gives a positive integer N in the range of long int.

Output Specification:

Factor N in the format N = p1^k1 * p2^k2 *…*pm^km, where pi's are prime factors of N in increasing order, and the exponent ki is the number of pi -- hence when there is only one pi, ki is 1 and must NOT be printed out.

Sample Input:
97532468
Sample Output:

97532468=2^2*11*17*101*1291

分析:

(1)题目要求是分解素因数的感觉。转化一下

(2)不用去判断每个除数是不是素数,从小到大第一个可以整除的必然的速数,然后就是判断商是不是素数,不是的话作为被除数继续循环。

(3)但是自己处理的不好,很多细节容易漏。回头优化一下代码

(4)商可能和之前的除数是一样要考虑到。这样4=2*2还是4=2^2可以验证。

(5)还要判断一开始是否vector为空,因为空的时候也可能i==start。这样逻辑不成立。

(6)综上之后抽时间优化代码吧。

#include <cstdio>
#include <math.h>
#include <map>
#include <vector>
using namespace std;
struct primeFactors {
	long int p,k;
};

int main (){
	long int N;
	vector<primeFactors> pf;
	scanf("%ld",&N);


	int start=2,i,n=N;
	
	while (n>1){
		bool flag=false;
		for (i=start;i<=sqrt((double)n);i++){
			if (n%i==0) {flag=true; break;}
		}
		if (flag==true){
			if (i!=start||pf.empty()==true){
				primeFactors p;
				p.p=i;
				p.k=1;
				pf.push_back(p);
			}
			else if (i==start){
				pf[pf.size()-1].k++;				
			}
	    n=n/i;
		start=i;
		}
		else if (flag==false){
			if (n!=start){
			primeFactors p;
			p.p=n;
			p.k=1;
			pf.push_back(p);}
			else {
				pf[pf.size()-1].k++;	
			}
			break;
		}
	//	printf("%d",int(flag));
	}

	printf("%ld=",N);
	if (N==1) printf("1");
	else {
	for (i=0;i<pf.size();i++){
		if (i==0)printf("%ld",pf[i].p);
		else printf("*%ld",pf[i].p);	
		if (pf[i].k>1)printf("^%d",pf[i].k);
	}
	}

//	printf("1");
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值