【问题标题】:sum of divisors of all divisors of a number一个数的所有除数的除数之和
【发布时间】:2019-02-11 10:24:43
【问题描述】:

以下方法的很好解释是here。由于格式问题,我无法在这里写。

// C++ 程序求所有除数之和 自然数的除数。

#include<bits/stdc++.h> 
using namespace std; 

// Returns sum of divisors of all the divisors 
// of n 
int sumDivisorsOfDivisors(int n) 
{ 
    // Calculating powers of prime factors and 
    // storing them in a map mp[]. 
    map<int, int> mp; 
    for (int j=2; j<=sqrt(n); j++) 
    { 
        int count = 0; 
        while (n%j == 0) 
        { 
            n /= j; 
            count++; 
        } 

        if (count) 
            mp[j] = count; 
    } 

    // If n is a prime number 
    if (n != 1) 
        mp[n] = 1; 

    // For each prime factor, calculating (p^(a+1)-1)/(p-1) 
    // and adding it to answer. 
    int ans = 1; 
    for (auto it : mp) 
    { 
        int pw = 1; 
        int sum = 0; 

        for (int i=it.second+1; i>=1; i--) 
        { 
            sum += (i*pw); 
            pw *= it.first; 
        } 
        ans *= sum; 
    } 

    return ans; 
} 

// Driven Program 
int main() 
{ 
    int n = 10; 
    cout << sumDivisorsOfDivisors(n); 
    return 0; 
} 

我没有得到这个循环中发生的事情,而不是添加到他们正在乘以总和,他们如何计算(p^(a+1)-1)/(p-1) 和这个到 ans。任何人都可以帮助我了解这个循环背后的直觉。

我从here得到这个

for (auto it : mp) 
{ 
    int pw = 1; 
    int sum = 0; 

    for (int i=it.second+1; i>=1; i--) 
    { 
        sum += (i*pw); 
        pw *= it.first; 
    } 
    ans *= sum; 
}

【问题讨论】:

  • 到目前为止您是否尝试过调试?
  • 第一个循环是获取素数除数,以及它们作为因子的次数。 (例如,如果能被 8 整除,则因子为 2,计数为 3)。顺便说一句,代码不是计算所有除数的总和 - 它是计算可能的主要除数的最高幂的总和(例如,如果该值可被 8 整除,则总和将包括 8,但不包括 4 或 2)。这可能会从总和中遗漏几个除数。
  • 我认为您对 添加 它来回答感到困惑。 由于另一个素除数而产生的除数取决于所有其他除数,因此这是一个乘法运算。
  • 'Divisors of divisors' 是一个非常奇怪的术语。您是指“主要因素”吗?

标签: c++ algorithm discrete-mathematics number-theory


【解决方案1】:

首先考虑这个说法:

(p10 + p11 +…+ p1k1) * (p20 + p 21 +…+ p2k2)

现在,任何 pa 的除数,对于 p 作为素数,是 p0, p1,……, pa,除数之和为:

((p10) + (p10 + p1 sub>1) + .... + (p10 + p11 + ...+ pk1)) * ((p20) + ( p20 + p21) + (p2 0 + p21 + p22) + ... (p20 + p21 + p22 + .. + p2k2))

你可以认为上面的语句等同于下面的语句:

[[p10 * (k1 + 1) + p11 * k1 + p12 * (k1 - 1 ) + ... . + (p1k1 * 1) ]] * [[p20 * (k2 + 1) + p21 * (k2) + p22 * (k2 - 1 ) + .... + (p2k2 * 1) ]] 在您在帖子中编写的代码中,最后一条语句已实现。

例如,如果您考虑 n = 54 = 33 * 21
ans 以这种格式计算:

ans = (20 * 2 + 21 * 1) * (30 * 4 + 31 * 3 + 32 * 2 + 33 *1) = 4 * 58 = 232

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2017-06-24
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多