5.5 PAT A 1059 Prime Factors (25分)(质因子分解)

1059 Prime Factors (25分)

Given any positive integer NNN, you are supposed to find all of its prime factors, and write them in the format NNN = p1k1×p2k2×⋯×pmkm{p_1}^{k_1}\times {p_2}^{k_2} \times \cdots \times {p_m}^{k_m}p​1​​​k​1​​​​×p​2​​​k​2​​​​×⋯×p​m​​​k​m​​​​.

Input Specification:

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

Output Specification:

Factor NNN in the format NNN = p1p_1p​1​​^k1k_1k​1​​*p2p_2p​2​​^k2k_2k​2​​**pmp_mp​m​​^kmk_mk​m​​, where pip_ip​i​​'s are prime factors of NNN in increasing order, and the exponent kik_ik​i​​ is the number of pip_ip​i​​ -- hence when there is only one pip_ip​i​​, kik_ik​i​​ is 1 and must NOT be printed out.

Sample Input:

97532468

Sample Output:

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

给定一个正整数,求它的质因子分解。先利用素数打表获取质数,然后判断是否是其因子。利用结构体factor存储质因子。

参考代码:

#include <cstdio>
#include <cmath> 
#include <cstring>
const int maxn=100010;
struct factor{
	int x,cnt; //x为质因子,cnt为数目 
}fac[10]; 
int pri[100010] ,pnum;
bool p[maxn];
void findprime(int n)
{
	for(int i=2;i<maxn;++i)
	{
		if(p[i]==false)
		{
			pri[pnum++]=i;
			for(int j=i+i;j<maxn;j+=i)
			{
				p[j]=true;
			}	
		}
	}
}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		memset(p,0,sizeof(p));
		pnum=0;
		findprime(n);
		int count=0;
		if(n==1)
			printf("1=1\n"); //特判1 
		else
		{
			printf("%d=",n);
			int sqr=(int)sqrt(1.0*n);
			for(int i=0;i<pnum&&pri[i]<=sqr;++i)
			{
				if(n%pri[i]==0)
				{
					fac[count].x=pri[i];
					fac[count].cnt=0;
					while(n%pri[i]==0)
					{
						fac[count].cnt++;
						n/=pri[i];
					}
					count++;
				}
				if(n==1)
					break;
			}
			if(n!=1)
			{
				fac[count].x=n;
				fac[count].cnt=1;
				count++;
			}
			for(int i=0;i<count;++i)
			{
				if(i>0)
					printf("*");
				printf("%d",fac[i].x);
				if(fac[i].cnt>1)
					printf("^%d",fac[i].cnt);
			}
			printf("\n");
		}
		
	}
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/qq_43590614/article/details/105119973