【发布时间】: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