简体   繁体   中英

sum of divisors of all divisors of a number

The very well explanation of below approach is here .I was not able to write here due to formatting issues.

// C++ program to find sum of divisors of all the divisors of a natural number.

#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; 
} 

I am not getting what is happening in this loop instead of adding to ans they are multiplying sum ,how they are calculating (p^(a+1)-1)/(p-1) and this to ans.can anyone help me with the intuition behind this loop.

I got this from 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; 
}

First consider this statement:

(p 1 0 + p 1 1 +…+ p 1 k 1 ) * (p 2 0 + p 2 1 +…+ p 2 k 2 )

Now, the divisors of any p a , for p as prime, are p 0 , p 1 ,……, p a , and sum of diviors will be :

((p 1 0 ) + (p 1 0 + p 1 1 ) + .... + (p 1 0 + p 1 1 + ...+ p k 1 )) * ((p 2 0 ) + (p 2 0 + p 2 1 ) + (p 2 0 + p 2 1 + p 2 2 ) + ... (p 2 0 + p 2 1 + p 2 2 + .. + p 2 k 2 ))

you can consider the above statement equivalent to bellow statement:

[[p 1 0 * (k 1 + 1) + p 1 1 * k 1 + p 1 2 * (k 1 - 1 ) + .... + (p 1 k 1 * 1) ]] * [[p 2 0 * (k 2 + 1) + p 2 1 * (k 2 ) + p 2 2 * (k 2 - 1 ) + .... + (p 2 k 2 * 1) ]] in the code that you write in the post, the last statement was implemented.

for example if you consider n = 54 = 3 3 * 2 1 ,
the ans is calculated in this format:

ans = (2 0 * 2 + 2 1 * 1) * (3 0 * 4 + 3 1 * 3 + 3 2 * 2 + 3 3 *1) = 4 * 58 = 232

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM