约数个数和约数之和算法总结

知识概览

约数个数

基于算数基本定理,假设N分解质因数的结果为

N = p_1^{\alpha_{1}}p_2^{\alpha_{2}} \cdots p_k^{\alpha_{k}}

可得对于N的任何一个约数d,有

d = p_1^{\beta_{1}}p_2^{\beta_{2}} \cdots p_k^{\beta_{k}}, 0\leqslant \beta_{i}\leqslant \alpha_{i}

因为N的每一个约数和\beta_{1}~\beta_{k}的一种选法是一一对应的,根据乘法原理可得,

一个数的约数个数为

(\alpha_{1} + 1)(\alpha_{2} + 1) \cdots (\alpha_{k} + 1)

约数之和

一个数的约数之和公式为

(p_1^{0} + p_1^{1} + \cdots + p_1^{\alpha_1})\cdots (p_k^{0} + p_k^{1} + \cdots + p_k^{\alpha_k})

多项式乘积的每一项为

p_1^{\beta_{1}}p_2^{\beta_{2}} \cdots p_k^{\beta_{k}}

正好对应的是一个数的每一个约数。

例题展示

约数个数

题目链接

活动 - AcWing系统讲解常用算法与数据结构,给出相应代码模板,并会布置、讲解相应的基础算法题目。icon-default.png?t=N7T8https://www.acwing.com/problem/content/872/

代码
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

typedef long long LL;

const int mod = 1e9 + 7;

int main()
{
    int n;
    cin >> n;
    
    unordered_map<int, int> primes;
    while (n--)
    {
        int x;
        cin >> x;
        
        for (int i = 2; i <= x / i; i++)
            while (x % i == 0)
            {
                x /= i;
                primes[i]++;
            }
            
        if (x > 1) primes[x]++;
    }
    
    LL res = 1;
    for (auto prime : primes) res = res * (prime.second + 1) % mod;
    
    cout << res << endl;
    
    return 0;
}

约数之和

题目链接

活动 - AcWing系统讲解常用算法与数据结构,给出相应代码模板,并会布置、讲解相应的基础算法题目。icon-default.png?t=N7T8https://www.acwing.com/problem/content/873/

代码
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

typedef long long LL;

const int mod = 1e9 + 7;

int main()
{
    int n;
    cin >> n;
    
    unordered_map<int, int> primes;
    while (n--)
    {
        int x;
        cin >> x;
        
        for (int i = 2; i <= x / i; i++)
            while (x % i == 0)
            {
                x /= i;
                primes[i]++;
            }
            
        if (x > 1) primes[x]++;
    }
    
    LL res = 1;
    for (auto prime : primes)
    {
        int p = prime.first, a = prime.second;
        LL t = 1;
        while (a--) t = (t * p + 1) % mod;
        res = res * t % mod;
    }
    
    cout << res << endl;
    
    return 0;
}

参考资料

  1. AcWing算法基础课
  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ykycode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值