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 N = {p_1}^{k_1}×{p_2}^{k_2}×⋯×{p_m}^{k_m} N=p1k1×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
1
k
1
×
p
2
k
2
×
⋯
×
p
m
k
m
N = {p_1}^{k_1}×{p_2}^{k_2}×⋯×{p_m}^{k_m}
N=p1k1×p2k2×⋯×pmkm
where
p
i
p_i
pi’s are prime factors of N in increasing order, and the exponent
k
i
k_i
ki is the number of
p
i
p_i
pi – hence when there is only one
p
i
p_i
pi ,
k
i
k_i
ki is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^211171011291
题目大意:题意很简单,就是将输入的数分解为质数的乘积。
解题思路:既然需要将数分解为质数的乘积,首先就要找出哪些数是质数,这里我使用常用的埃式筛法,简而言之就是从2开始,如果当前的数是素数,则将当前的数的所有倍数标记为非素数,最后未被标记的数就是素数。判断素数的方法有了,但是范围如何确定?本题中说输入的n范围为long int的范围,这样如果输入的数为long int最大值附近的质数,那我们筛选素数的范围也要逼近long int才行,理论上是这样,但事实上本题只需求出<500000(参考自柳婼 の blog)的素数就行(这个应该是测试样例的问题)。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long int li;
const int maxn = 500000;
vector<int> prime(maxn, 1);
int main(int argc, char const *argv[])
{
for(int i = 2;i < maxn; i++){
for(int j = 2*i;j < maxn; j+=i)
prime[j] = 0;
}
li n;
map<li,li> mp;
cin >> n;
cout << n << "=" ;
if(n == 1){
cout << 1 << endl;
return 0;
}
int factor = 2;
while(n >= 2){
while(n % factor == 0 && prime[factor] == 1){
mp[factor]++;
n /= factor;
}
factor++;
}
map<li,li>::iterator it = mp.begin();
for(;it != mp.end(); it++){
if(it != mp.begin())
cout << "*";
cout << it->first;
if(it->second >= 2)
cout << "^" << it->second;
}
return 0;
}
本文介绍了一种质因数分解算法,通过埃式筛法预处理小范围内的所有质数,然后利用这些质数对任意正整数进行质因数分解,并以特定格式输出分解结果。
1877

被折叠的 条评论
为什么被折叠?



