官术网_书友最值得收藏!

  • The Modern C++ Challenge
  • Marius Bancila
  • 226字
  • 2021-06-25 22:01:23

6. Abundant numbers

An abundant number, also known as an excessive number, is a number for which the sum of its proper pisors is greater than the number itself. The proper pisors of a number are the positive prime factors of the number, other than the number itself. The amount by which the sum of proper pisors exceeds the number itself is called abundance. For instance, the number 12 has the proper pisors 1, 2, 3, 4, and 6. Their sum is 16, which makes 12 an abundant number. Its abundance is 4 (that is, 16 - 12).

To determine the sum of proper pisors, we try all numbers from 2 to the square root of the number (all prime factors are less than or equal to this value). If the current number, let’s call it i, pides the number, then i and num/i are both pisors. However, if they are equal (for example, if i = 3, and n = 9, then i pides 9, but n/i = 3), we add only i because proper pisors must only be added once. Otherwise, we add both i and num/i and continue:

int sum_proper_pisors(int const number)
{
int result = 1;
for (int i = 2; i <= std::sqrt(number); i++)
{
if (number%i == 0)
{
result += (i == (number / i)) ? i : (i + number / i);
}
}
return result;
}

Printing abundant numbers is as simple as iterating up to the specified limit, computing the sum of proper pisors and comparing it to the number:

void print_abundant(int const limit)
{
for (int number = 10; number <= limit; ++number)
{
auto sum = sum_proper_pisors(number);
if (sum > number)
{
std::cout << number << ", abundance="
<< sum - number << std::endl;
}
}
}

int main()
{
int limit = 0;
std::cout << "Upper limit:";
std::cin >> limit;

print_abundant(limit);
}
主站蜘蛛池模板: 揭西县| 威信县| 吴堡县| 闵行区| 南涧| 佳木斯市| 太谷县| 泰顺县| 都匀市| 晋州市| 东乡县| 都江堰市| 琼海市| 灵川县| 白银市| 黄山市| 鹰潭市| 临沭县| 溧水县| 梁河县| 泸定县| 合作市| 连平县| 新绛县| 威远县| 全椒县| 横山县| 瑞昌市| 灵台县| 鹤壁市| 江孜县| 怀柔区| 集安市| 竹山县| 定陶县| 南川市| 巧家县| 宜川县| 南木林县| 仲巴县| 新野县|