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.