Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1* p2^k2 *…*pm^km.
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:97532468Sample Output:
97532468=2^2*11*17*101*1291
分析:
(1)题目要求是分解素因数的感觉。转化一下
(2)不用去判断每个除数是不是素数,从小到大第一个可以整除的必然的速数,然后就是判断商是不是素数,不是的话作为被除数继续循环。
(3)但是自己处理的不好,很多细节容易漏。回头优化一下代码
(4)商可能和之前的除数是一样要考虑到。这样4=2*2还是4=2^2可以验证。
(5)还要判断一开始是否vector为空,因为空的时候也可能i==start。这样逻辑不成立。
(6)综上之后抽时间优化代码吧。
#include <cstdio>
#include <math.h>
#include <map>
#include <vector>
using namespace std;
struct primeFactors {
long int p,k;
};
int main (){
long int N;
vector<primeFactors> pf;
scanf("%ld",&N);
int start=2,i,n=N;
while (n>1){
bool flag=false;
for (i=start;i<=sqrt((double)n);i++){
if (n%i==0) {flag=true; break;}
}
if (flag==true){
if (i!=start||pf.empty()==true){
primeFactors p;
p.p=i;
p.k=1;
pf.push_back(p);
}
else if (i==start){
pf[pf.size()-1].k++;
}
n=n/i;
start=i;
}
else if (flag==false){
if (n!=start){
primeFactors p;
p.p=n;
p.k=1;
pf.push_back(p);}
else {
pf[pf.size()-1].k++;
}
break;
}
// printf("%d",int(flag));
}
printf("%ld=",N);
if (N==1) printf("1");
else {
for (i=0;i<pf.size();i++){
if (i==0)printf("%ld",pf[i].p);
else printf("*%ld",pf[i].p);
if (pf[i].k>1)printf("^%d",pf[i].k);
}
}
// printf("1");
return 0;
}