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:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
题意:
求一个整数的质因数分解。
思路:
对于一个整数来说,它的因子一定是在sqrt(n)左右成对出现的,所以大于sqrt(n)的质因子至多只会出现一个。因此我们只需要统计sqrt(10^10)以内的素数。在对n来因式分解。
- 找素数的方法有两种,一种是遍历2到sqrt(i)内有没有能整除的数,没有则为素数,找出范围内所有的素数。第二种是筛法,将从2开始将素数的倍数全部筛除,如,2,3,4,5,6,7,8,9,10…,还剩3,5,7,9然后3就是素数,再把3的倍数筛除,还剩5,7,那么5就是素数,再筛5的倍数,以此类推。
- 其次是因式分解,从素数集合中(从2开始),如果n能整除prime[i],那么就有这个素数,n/prime[i],在判断,进行统计拥有这个素数的个数。如果遍历到sqrt(n)以内的素数数为止n的值没有变为1,就是说存在一个大于sqrt(n)的质因子,此时那个质因子即为n。如:15,判断sqrt(15)内的素数(2和3),2不可以整除于是判断3是否可以整除,可以,于是n=n/3=5,个数为1,此时遍历完素数,n!=1,那么还有一个质因子即为n=5;
参考代码:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const int maxn=1e5;
vector<int> prime;
bool p[maxn]={false};
struct faction{
int p,k;
}fac[10];
void find_prime(){
for(int i=2;i<maxn;i++){
if(!p[i]){
prime.push_back(i);
for(int j=i+i;j<maxn;j+=i)
p[j]= true;
}
}
}
int main() {
int n;
scanf("%d",&n);
printf("%d=",n);
if(n==1)printf("1\n");
else{
find_prime();
int num=0;
for(int i=0;prime[i]<=sqrt(1.0*n);i++){
if(n%prime[i]==0){
fac[num].p=prime[i];
fac[num].k=0;
while(n%prime[i]==0){
fac[num].k++;
n/=prime[i];
}
num++;
}
if(n==1)break;
}
if(n!=1){
fac[num].p=n;
fac[num++].k=1;
}
for(int i=0;i<num;i++){
if(i!=0)printf("*");
if(fac[i].k!=1)printf("%d^%d",fac[i].p,fac[i].k);
else printf("%d",fac[i].p);
}
}
return 0;
}
如有错误,欢迎指正