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

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.

主站蜘蛛池模板: 武隆县| 桂东县| 江孜县| 胶南市| 中牟县| 河池市| 武陟县| 宁津县| 赣榆县| 外汇| 新疆| 太谷县| 厦门市| 若尔盖县| 枣阳市| 响水县| 日照市| 宽甸| 麻城市| 明水县| 屏东市| 荣成市| 余庆县| 枣强县| 普洱| 东辽县| 县级市| 宣恩县| 迁安市| 东海县| 邓州市| 芦山县| 阿拉善左旗| 禄劝| 溧阳市| 玉环县| 德州市| 涟水县| 融水| 利津县| 亳州市|