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

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

7. Amicable numbers

Two numbers are said to be amicable if the sum of the proper pisors of one number is equal to that of the other number. The proper pisors of a number are the positive prime factors of the number other than the number itself. Amicable numbers should not be confused with friendly numbers. For instance, the number 220 has the proper pisors 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, and 110, whose sum is 284. The proper pisors of 284 are 1, 2, 4, 71, and 142; their sum is 220. Therefore, the numbers 220 and 284 are said to be amicable.

The solution to this problem is to iterate through all the numbers up to the given limit. For each number, compute the sum of its proper pisors. Let’s call this sum1. Repeat the process and compute the sum of the proper pisors of sum1. If the result is equal to the original number, then the number and sum1 are amicable numbers:

void print_amicables(int const limit)
{
for (int number = 4; number < limit; ++number)
{
auto sum1 = sum_proper_pisors(number);
if (sum1 < limit)
{
auto sum2 = sum_proper_pisors(sum1);
if (sum2 == number && number != sum1)
{
std::cout << number << "," << sum1 << std::endl;
}
}
}
}

In the above sample, sum_proper_pisors() is the function seen in the solution to the abundant numbers problem.

The above function prints pairs of numbers twice, such as 220,284 and 284,220. Modify this implementation to only print each pair a single time.

主站蜘蛛池模板: 黄龙县| 土默特左旗| 江华| 乌恰县| 图木舒克市| 本溪市| 左贡县| 拜泉县| 武义县| 荃湾区| 凌云县| 修文县| 静安区| 乐业县| 长宁县| 承德市| 栾城县| 石家庄市| 平和县| 云梦县| 隆安县| 广安市| 惠来县| 靖西县| 砀山县| 缙云县| 辛集市| 榆林市| 洛阳市| 伊吾县| 颍上县| 南郑县| 辽源市| 吴堡县| 肇源县| 遵义市| 杭锦后旗| 井研县| 武隆县| 乌拉特前旗| 东乌珠穆沁旗|