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

19. Armstrong numbers

The obvious approach to this problem is to loop through the candidate numbers, convert each into a string, pull apart its digits, raise the digits to the correct power, and see if they add up to the original number.

The following method loops through values up to the desired maximum to build a list of Armstrong numbers:

// Look for Armstrong numbers <= max.
private List<long> FindArmstrongNumbers(long max)
{
List<long> values = new List<long>();
for (long i = 1; i <= max; i++)
if (IsArmstrong(i)) values.Add(i);
return values;
}

This method calls the following IsArmstrong method to see if a value is an Armstrong number:

// Return true if this is an Armstrong number.
private bool IsArmstrong(long number)
{
// Get the number's digits.
long copy = number;
List<long> digits = new List<long>();
while (copy > 0L)
{
digits.Add(copy % 10L);
copy = copy / 10L;
}

// Add the digits' powers.
long total = 0;
long numDigits = digits.Count;
foreach (long digit in digits)
total += (long)Math.Pow(digit, numDigits);
return (total == number);
}

The only non-obvious pieces in this method are the two statements that calculate the digit and update the copy of the number. The calculation copy % 10L returns the number's least significant digit. For example, 417 % 10L returns 7.

The calculation copy / 10L returns the number with its least significant digit removed. For example, 417 % 10L returns 41.

Download the ArmstrongNumbers example solution to see additional details.

主站蜘蛛池模板: 扶绥县| 葵青区| 黄石市| 临江市| 灵宝市| 平罗县| 德昌县| 阳原县| 清镇市| 巴林左旗| 八宿县| 铁岭市| 九寨沟县| 商丘市| 惠州市| 乌恰县| 九龙坡区| 巩义市| 文昌市| 加查县| 高邑县| 灵石县| 中宁县| 蒲城县| 龙州县| 牡丹江市| 娄烦县| 合作市| 泌阳县| 莲花县| 抚远县| 金华市| 玛纳斯县| 海南省| 涞源县| 临海市| 宿州市| 都兰县| 齐河县| 普洱| 太谷县|