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}p1k1×p2k2×⋯×pmkm.
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_1p1^
k1k_1k1*
p2p_2p2^
k2k_2k2*
…*
pmp_mpm^
kmk_mkm, where pip_ipi's are prime factors of NNN in increasing order, and the exponent kik_iki is the number of pip_ipi -- hence when there is only one pip_ipi, kik_iki is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
题意:任意给出一个正整数,让你把它分解成若干个质数相乘的形式,然后按格式输出 。
思路:
1.数学知识:对于任意一个正整数N,可以把它分解成若干个质数相乘,其中因子要么在sqrtN左右两侧成对出现,要么就是sqrtN,并且大于sqrt(N)的因子最多只有一个。
2.可以从2--sqrtN进行遍历,只要n%i==0成立,就令n=n/i;最后如果n==1,说明不存在大于sqrtN的因子,否则仅存在一个。另外1要特殊处理。
参考代码:
#include<cstdio>
#include<cmath>
#include<map>
using namespace std;
int n;
map<int,int> mp;
void getFactor(int n){
int sqrtN=(int)sqrt(double(n));
for(int i=2;i<=sqrtN;i++){
while(n%i==0) {
n/=i;
mp[i]++;
}
}
if(n!=1) mp[n]++;
}
int main()
{
scanf("%d",&n);
if(n==1) {
printf("1=1\n");
return 0;
}
getFactor(n);
printf("%d=",n);
for(auto it=mp.begin();it!=mp.end();it++){
if(it!=mp.begin()) printf("*");
if(it->second==1)
printf("%d",it->first);
else printf("%d^%d",it->first,it->second);
}
return 0;
}