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 = p​1k1×p2k2×⋯×pmkm.

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 = p​1k1p2k2…*pmkm, 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、计算出N范围内的所有素数
2、素数从小到大开始被N除,如果能整除,那么它就是N的一个因子,记录这个因子,并且记录这个因子的数量。
最后n不为1时,将剩余的n也当做一个因子
3、格式化输出即可

#include 
#include 
#include 
using namespace std;
int fac[20]={0},num=0;
int cnt[20]={0};
const int maxn=100010;
bool is_prime(int n)
{
	if(n==1)
	  return false;
    for(int i=2;i<=sqrt(1.0*n);i++)
    	if(n%2==0)
 	      return false;
    return true;
} 
void find_prime(int n)
{	
	for(int i=2;i<=sqrt(1.0*n);i++)
	{
		if(is_prime(i))
		{	  
  		   while(n%i==0)
		   {
		    fac[num]=i; //统计质因数的个数 
			n/=i;
			cnt[num]++;
			if(n%i!=0) 
			  num++;
		   }    		
		}  

	}	
	if(n!=1) //如果无法被根号以内的质因子除尽 
	{
		fac[num]=n;
		cnt[num]=1;
		num++;	
	}		
}
int main()
{
	int N;
	cin>>N;
	if(N==1)
	{
		printf("1=1\n");
		return 0;
	}
	find_prime(N);	
	printf("%d=",N);
	for(int i=0;i<num;i++)
	{	
	    if(i>0)
		printf("*");
		printf("%d",fac[i]);
		if(cnt[i]>1)
		printf("^%d",cnt[i]);
	}
	printf("\n");		
	return 0;
}

你可能感兴趣的:(PAT,OJ试题)