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 = 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 N in the range of long int.
Output Specification:
Factor N in the format N = p~1~\^k~1~ * p~2~\^k~2~ *…*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
大致题意为:输入一个数后进行素因子分解。是一个复习素数相关知识的好题。
需要注意以下结论。
结论一:对于int型范围的数来说,最多分解出10个不同的质因子。
因为 2∗3∗5∗7∗11∗13∗17∗19∗23∗29>int32 2 ∗ 3 ∗ 5 ∗ 7 ∗ 11 ∗ 13 ∗ 17 ∗ 19 ∗ 23 ∗ 29 > i n t 32
结论二:如果它存在[2,n]范围内的质因子,要么这些质因子全部小于等于sqrt(n),要么只存在一个大于sqrt(n)的质因子,而其余质因子全部小于等于sqrt(n)。
分析:
- 利用素数筛法得到素数表,利用结论二我们只需要开sqrt(int32)大小的数组即可,约10^5^。
- 此处我利用map存储各个质因子的个数。
- 注意:需要特判1=1。
#include <iostream>
#include <map>
#include <cmath>
#include <algorithm>
using namespace std;
bool f_prime[100050] = { 1,1,0 };
vector<int> prime;
map<int, int> res;
void find_prime(int n)
{
for (int i = 2; i <= n; i++)
{
if (f_prime[i] == 0)
{
int t = i;
prime.push_back(t);
for (int j = 2; t <= n; j++)
{
f_prime[t] = 1;
t = i*j;
}
}
}
}
int main()
{
long int n, m;
cin >> n;
m = n;
int limit = sqrt(n);
find_prime(limit+1); // 避免n=2时,函数直接退出
int now = 0;
while (n > 1)
{
if (n%prime[now] == 0)
{
res[prime[now]]++;
n /= prime[now];
}
else now++;
if (now >= prime.size())break;
}
if (n>1||(n==1&&res.size()==0)) // 结论一以及特判1=1
{
res[n]++;
}
cout << m << "=";
map<int, int>::iterator ptr = res.begin();
cout << ptr->first;
if (ptr->second > 1)cout << "^" << ptr->second;
ptr++;
for (; ptr != res.end(); ptr++)
{
cout <<"*"<< ptr->first;
if (ptr->second > 1)cout << "^" << ptr->second;
}
return 0;
}