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

  • The Modern C# Challenge
  • Rod Stephens
  • 166字
  • 2021-08-13 15:23:58

18. Perfect numbers

You can modify the preceding solution to find perfect numbers. Because you only need to calculate the sum of each value's divisors once, there's no need to pre-calculate those values and store them in an array. That wouldn't cost you much time, but it would use up a bunch of unnecessary memory.

The following code shows a method that finds perfect numbers:

// Find perfect numbers <= max.
private List<long> FindPerfectNumbers(long max)
{
// Look for perfect numbers.
List<long> values = new List<long>();
for (int value = 1; value <= max; value++)
{
long sum = GetProperDivisors(value).Sum();
if (value == sum) values.Add(value);
}
return values;
}

This method loops through the values that are less than the maximum. For each value, it calls the GetProperDivisors method, which is used in the previous solution, and calls Sum to add the divisors. If the sum equals the original number, the code adds the number to its list of perfect numbers.

Download the PerfectNumbers example solution to see additional details.

主站蜘蛛池模板: 清水河县| 尼勒克县| 衡东县| 睢宁县| 宜良县| 黄梅县| 通化县| 花莲市| 彭泽县| 诏安县| 长阳| 巴青县| 泗水县| 宁陵县| 互助| 清水县| 潼关县| 丰原市| 临夏市| 昭通市| 云梦县| 无棣县| 渭源县| 竹溪县| 屏南县| 会东县| 雷波县| 谢通门县| 新平| 林周县| 六枝特区| 张掖市| 奉节县| 进贤县| 珲春市| 方正县| 孟连| 铜陵市| 原阳县| 嵊泗县| 修水县|