PAT(A) - 1059 Prime Factors (25) -- 质因子分解

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~^k~m~.

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

大致题意为:输入一个数后进行素因子分解。是一个复习素数相关知识的好题。

需要注意以下结论。

结论一:对于int型范围的数来说,最多分解出10个不同的质因子。

因为 2357111317192329>int32 2 ∗ 3 ∗ 5 ∗ 7 ∗ 11 ∗ 13 ∗ 17 ∗ 19 ∗ 23 ∗ 29 > i n t 32

结论二:如果它存在[2,n]范围内的质因子,要么这些质因子全部小于等于sqrt(n),要么只存在一个大于sqrt(n)的质因子,而其余质因子全部小于等于sqrt(n)。

分析:

  • 利用素数筛法得到素数表,利用结论二我们只需要开sqrt(int32)大小的数组即可,约10^5^。
  • 此处我利用map存储各个质因子的个数。
  • 注意:需要特判1=1。
#include <iostream>  
#include <map>  
#include <cmath>  
#include <algorithm> 
using namespace std;  

bool f_prime[100050] = { 1,1,0 };
vector<int> prime;
map<int, int> res;
void find_prime(int n)
{
    for (int i = 2; i <= n; i++)
    {
        if (f_prime[i] == 0)
        {
            int t = i;
            prime.push_back(t);
            for (int j = 2; t <= n; j++)
            {
                f_prime[t] = 1;
                t = i*j;
            }
        }
    }
}

int main() 
{
    long int n, m;
    cin >> n;
    m = n;
    int limit = sqrt(n);
    find_prime(limit+1); // 避免n=2时,函数直接退出
    int now = 0;
    while (n > 1)
    {
        if (n%prime[now] == 0)
        {
            res[prime[now]]++;
            n /= prime[now];
        }
        else now++;
        if (now >= prime.size())break;
    }
    if (n>1||(n==1&&res.size()==0)) // 结论一以及特判1=1
    {
        res[n]++;
    }
    cout << m << "=";
    map<int, int>::iterator ptr = res.begin();
    cout << ptr->first;
    if (ptr->second > 1)cout << "^" << ptr->second;
    ptr++;
    for (; ptr != res.end(); ptr++)
    {
        cout <<"*"<< ptr->first;
        if (ptr->second > 1)cout << "^" << ptr->second;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值