Armstrong Numbers
Decide whether a number equals the sum of its digits, each raised to the power of the digit count.
Adapted from Exercism’s problem specification (MIT). Listed under Numbers & Math.
// FILE: armstrong_numbers.nomi
//# Armstrong numbers: numbers that are the sum of their own digits, each
//# raised to the power of the number of digits.
/// Reports whether `number` is the sum of its own digits, each raised to
/// the power of the number of digits: `153 == 1^3 + 5^3 + 3^3`.
pub fn is_armstrong(number: Int) -> Bool
if number < 0 then return False
digits = Int.to_digits(number)
width = Iter.count(digits)
total =
digits
|> Iter.map(&Int.pow(&1, width))
|> Iter.sum()
total == number
end
// FILE: armstrong_numbers_test.nomi
import armstrong_numbers
test "recognizes Armstrong numbers"
[
("Zero is an Armstrong number", 0, True),
("Single-digit numbers are Armstrong numbers", 5, True),
("There are no two-digit Armstrong numbers", 10, False),
("Three-digit number that is an Armstrong number", 153, True),
("Three-digit number that is not an Armstrong number", 100, False),
("Four-digit number that is an Armstrong number", 9474, True),
("Four-digit number that is not an Armstrong number", 9475, False),
("Seven-digit number that is an Armstrong number", 9926315, True),
("Seven-digit number that is not an Armstrong number", 9926314, False),
("Armstrong number containing seven zeroes", 186709961001538790100634132976990, True),
("The largest and last Armstrong number", 115132219018763992565095597973971522401, True),
]
|> subtests (description, number, expected), description
assert armstrong_numbers.is_armstrong(number) == expected
end
endok recognizes Armstrong numbers (11 cases)
test result: ok. 11 passed, 0 failed
How it’s written
Section titled “How it’s written”- The digits come from
Int.to_digits, rather than from"${number}"andString.to_intper grapheme. The arithmetic stays inIntand needs noMaybeto unwrap, andInt.to_digits(0)is[0], so zero needs no early return. - Each digit is raised with
Int.powin a capture,&Int.pow(&1, width). - The sum is bound as
totaland compared on its own line, rather than piped into athen &(&1 == number)stage. - The eleven canonical cases are one
subteststable, the 33-digit and 39-digit Armstrong numbers included: anIntis exact at any size, sois_armstrongtakes them as it takes 153.