「1059」Prime Factors

本文探讨了一种高效的质因数分解算法,通过避免建立素数表,利用最小素因子的特性,实现在O(sqrt(N))时间内分解大整数。策略包括循环优化、最小因子判断和计数器管理,适用于解决经典分解问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format ​.

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

Ω

经典分解质因数,感觉已经不会做大一的题目了,真的年纪大了。

有两种思路,首先建立一个素数表,我们知道一个数的质因数不会超过其平方根,那么由于,因此我们只需找出所有5000以内的素数然后一个一个素数去除。

这种做法没什么美感。我采取了一点优化,不建立素数表,首先可以肯定最小的因数一定是素数,否则还会存在更小的因数而矛盾。根据这一条性质,我们只需每次找最小的因子即可,必然是素数,然后接着找的最小素因子,周而复始。另外循环搜索的范围也不必从2开始,根据我们的策略可以发现每轮发现的最小素因子必然上一轮找到的最小素因子(否则必然更早找到),因此可以将循环范围定为(事实证明更快)。另外每找到一个就更新并重新开始循环,直到不再变化为止。

如此一来,我们就能对搜索区间的两端同时进行优化,运行时用一个map记录每个出现的次数最后统一输出即可。


#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<int, int> pf;
    int n, m = -1, pre = 2;
    cin >> n;
    cout << n << "=";
    if (n == 1) cout << "1";
    else
    {
        while (m != n)
        {
            m = n;
            for (int i = pre; i <= n / 2; ++i)
                if (n % i == 0)
                {
                    pf[i] += 1;
                    n /= (pre = i);
                    break;
                }
        }
        pf[n] += 1;
        bool flag = true;
        for (auto &k: pf)
            cout << (flag ? (flag = false, "") : "*") << k.first << (k.second == 1 ? "" : "^" + to_string(k.second));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值