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 = 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
https://www.patest.cn/contests/pat-a-practise/1059
https://www.nowcoder.com/pat/5/problem/4112
思路:
对于每一个数进行扫描,从2开始,每找到一个因子,不断相除,累加该因子次数。
——PAT AC,牛客网超时
对于每个数先判断是否是质数,如果是则不用再分解
——AC
CODE:
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
typedef struct S
{
int nu;
int p;
};
vector<S> pri;
bool pr(int n)
{
if (n==1||n==2||n==3) return 1;
for (int i=2;i*i<=n;i++)
if (n%i==0) return 0;
return 1;
}
int main()
{
int n;
cin>>n;
cout<<n<<"=";
if (pr(n))
{
cout<<n;
}
else
{
int i=2;
while (i<=n)
{
if (n%i==0)
{
S t;
t.nu=i;
t.p=0;
while (n%i==0)
{
t.p++;
n/=i;
}
pri.push_back(t);
}
i++;
}
for (int i=0;i<pri.size()-1;i++)
{
cout<<pri[i].nu;
if (pri[i].p!=1)
{
cout<<"^"<<pri[i].p;
}
cout<<"*";
}
cout<<pri[pri.size()-1].nu;
if (pri[pri.size()-1].p!=1)
{
cout<<"^"<<pri[pri.size()-1].p;
}
}
return 0;
}