[英]sum of divisors of all divisors of a number
以下方法的很好解釋是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;
}
我沒有得到這個循環中發生的事情,而不是添加到他們正在乘以總和的 ans,他們如何計算(p^(a+1)-1)/(p-1)
和這個 ans.誰能幫助我用這個循環背后的直覺。
我從這里得到這個
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;
}
首先考慮這個語句:
(p 1 0 + p 1 1 +…+ p 1 k 1 ) * (p 2 0 + p 2 1 +…+ p 2 k 2 )
現在,任何 p a的除數,對於 p 作為素數,是 p 0 , p 1 ,……, p a ,並且除數的總和將是:
((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 ))
您可以將上述語句視為等效於以下語句:
[[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) ]] 在你的代碼中寫在帖子里,最后一句被執行了。
例如,如果您考慮 n = 54 = 3 3 * 2 1 ,
ans 以這種格式計算:
ans = (2 0 * 2 + 2 1 * 1) * (3 0 * 4 + 3 1 * 3 + 3 2 * 2 + 3 3 *1) = 4 * 58 = 232
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.