PTA(Advanced Level)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 = p1kp2k2×⋯×pmk**m.

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**p**m^k**m, where p**i's are prime factors of N in increasing order, and the exponent k**i is the number of p**i -- hence when there is only one p**i, k**i is 1 and must NOT be printed out.

Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
思路
  • 质因数分解和因数分解类似,只是要先得到质数表,我这里使用的是质数筛法
  • (N)的最大是(2^{31}-1)(sqrt{n}approx2^{15.5}),除非这个数本身是质数,不然我们因子判断到(sqrt{n})就好了
代码
#include<bits/stdc++.h>
using namespace std;
struct factor
{
	int x;	//质数
	int n;	//阶数
}fac[50];   
int primes[100100];
int prime_length = 0;
void gen_prime()
{
	int MAXN = 100100;
	bool flag[MAXN] = {0};
	for(int i=2;i<MAXN;i++)
	{
		if(!flag[i])
		{
			primes[prime_length++] = i;
			for(int j=i+i;j<MAXN;j+=i)	flag[j] = true;
		}
	}
}//质数筛法

int main()
{
	int n, n_copy;
	cin >> n;
	n_copy = n;
    gen_prime();

	int last_pos = 0;
	if(n == 1)	cout << "1=1";		//1是特殊情况
	else
	{
		int sqrt_value = (int)sqrt(n * 1.0);	//一个数的因子除了自身不会超过自身的根号n
		for(int i=0;primes[i]<sqrt_value && i<prime_length;i++)		//不超过根号n,以及不超过质数表的长度
		{
			while(n % primes[i] == 0)
			{
				fac[last_pos].x = primes[i];
				fac[last_pos].n == 0;
				while(n % primes[i] == 0)
				{
					fac[last_pos].n++;
					n /= primes[i];
				}
				last_pos++;
			}
			if(n == 1)  break;
		}

		if(n != 1)	//说明自己本身就是质数了
		{
			fac[last_pos].x = n;
			fac[last_pos].n = 1;
			last_pos++;
		}


		cout << n_copy << "=";
		for(int i=0;i<last_pos;i++)
		{
			if(fac[i].n != 1)
				printf("%d^%d", fac[i].x, fac[i].n);
			else
				printf("%d", fac[i].x);
			if(i != last_pos - 1)
				printf("*");
		}
	}
	return 0;
}

引用

https://pintia.cn/problem-sets/994805342720868352/problems/994805415005503488

原文地址:https://www.cnblogs.com/MartinLwx/p/12538484.html