【PAT甲级A1059】Prime Factors (25分)(c++)

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 = p​1^​​ ​k​1​​ ​​ × p​2 ^​​ ​k​2​ ​​ ×⋯× p​m​^​ ​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 = p​1​​ ^k​1​​ *p​2​​ ^k​2​​ *…*p​m​​ ^k​m
​​ , where p​i​​ 's are prime factors of N in increasing order, and the exponent k​i​​ is the number of p​i​​ – hence when there is only one p​i​​ , k​i​​ 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;
}

如有错误,欢迎指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值