PAT-1059 Prime Factors

题目描述

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.

输入描述:

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

输出描述:

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.

输入例子:

97532468

输出例子:

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

    求质因子,注意如果正整数N存在大于\large \sqrt{N}的质因子的话,有且只有一个。所以质数表求到\large \sqrt{N},N除掉质数表中所有质因子还大于1,说明有一个大于\large \sqrt{N}的质因子,把这个数存到质因子列表中输出即可。

#include
#include
#include
#define MAX 100000
int prime[MAX]={0};
bool t[MAX];
int num=0;

int main(){
	long long n,m;
	scanf("%lld",&m);
	n=m;
	if(n==1){printf("1=1");return 0;}
	std::fill(t,t+MAX,true);
	for(int i=2;i fac;
	int i=0;

	for(int i=0;i1;i++){
		if(n%prime[i]==0){
			fac[prime[i]]=1;n/=prime[i];
			while(n%prime[i]==0&&n>0){
				fac[prime[i]]++;
				n/=prime[i];
			}
		}
	}
	if(n>1){
		fac[n]=1;//最多一个大于N^0.5的质因子
	}
	printf("%lld=",m);
	
	
	for(auto it=fac.begin();it!=fac.end();it++){
		if(it!=fac.begin())
			printf("*");
		printf("%lld",it->first);
		if(it->second>1)
			printf("^%d",it->second);
	}

	return 0;
}

 

你可能感兴趣的:(浙大PAT-Advanced)