Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format .
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*
…*
pm^
km, 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
Ω
经典分解质因数,感觉已经不会做大一的题目了,真的年纪大了。
有两种思路,首先建立一个素数表,我们知道一个数的质因数不会超过其平方根,那么由于,因此我们只需找出所有5000以内的素数然后一个一个素数去除。
这种做法没什么美感。我采取了一点优化,不建立素数表,首先可以肯定最小的因数一定是素数,否则还会存在更小的因数而矛盾。根据这一条性质,我们只需每次找最小的因子即可,必然是素数,然后接着找的最小素因子,周而复始。另外循环搜索的范围也不必从2开始,根据我们的策略可以发现每轮发现的最小素因子必然上一轮找到的最小素因子(否则必然更早找到),因此可以将循环范围定为(事实证明比更快)。另外每找到一个就更新并重新开始循环,直到不再变化为止。
如此一来,我们就能对搜索区间的两端同时进行优化,运行时用一个map记录每个出现的次数最后统一输出即可。
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, int> pf;
int n, m = -1, pre = 2;
cin >> n;
cout << n << "=";
if (n == 1) cout << "1";
else
{
while (m != n)
{
m = n;
for (int i = pre; i <= n / 2; ++i)
if (n % i == 0)
{
pf[i] += 1;
n /= (pre = i);
break;
}
}
pf[n] += 1;
bool flag = true;
for (auto &k: pf)
cout << (flag ? (flag = false, "") : "*") << k.first << (k.second == 1 ? "" : "^" + to_string(k.second));
}
}