约数

Posted on 2023-02-24 15:24  lyc2002  阅读(34)  评论(0编辑  收藏  举报

试除法求约数

时间复杂度

O(√n)

代码

vector<int> get_divisors(int x)
{
    vector<int> res;
    
    for (int i = 1; i <= x / i; i++)
        if (x % i == 0) {
            res.push_back(i);
            if (i != x / i) res.push_back(x / i);
        }
    
    sort(res.begin(), res.end());
    
    return res;
}

约数个数与约数之和

// h 储存分解出的质因数和其质数
unordered_map<int, int> h; 

//如果 x = p1^c1 * p2^c2 * ... *pk^ck
//约数个数: (c1 + 1) * (c2 + 1) * ... * (ck + 1)
for (auto elem : h)
    res = (LL)res * (elem.second + 1) % mod;

//约数之和: (p1^0 + p1^1 + ... + p1^c1) * ... * (pk^0 + pk^1 + ... + pk^ck)
for (auto elem : h) {
    int p = elem.first, a = elem.second;
    int t = 1;
    while (a--) t = ((LL)t * p + 1) % mod;
    res = (LL)res * t % mod;
}