Skip to content

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
end
  • The digits come from Int.to_digits, rather than from "${number}" and String.to_int per grapheme. The arithmetic stays in Int and needs no Maybe to unwrap, and Int.to_digits(0) is [0], so zero needs no early return.
  • Each digit is raised with Int.pow in a capture, &Int.pow(&1, width).
  • The sum is bound as total and compared on its own line, rather than piped into a then &(&1 == number) stage.
  • The eleven canonical cases are one subtests table, the 33-digit and 39-digit Armstrong numbers included: an Int is exact at any size, so is_armstrong takes them as it takes 153.