Problem of the Day
A new programming or logic puzzle every Mon-Fri

Armstrong Numbers

Today's objective is to create a program that finds all the Armstrong Numbers from 10 to 10000 inclusive. An Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is considered an Armstrong Number 1^3 + 5^3 +3^3 = 153.

Permalink: http://problemotd.com/problem/armstrong-numbers/

Comments:

  • Jason Brady - 10 years, 3 months ago

    In Haskell

    main :: IO ()
    main = print $ filter isArmstrong [10..10000]
    
    isArmstrong :: Int -> Bool
    isArmstrong n = armstrong n == n
      where 
        armstrong 0 = 0
        armstrong x = d^p + armstrong r
          where (r, d) = x `divMod` 10
        p = length $ digits n
        digits 0 = []
        digits x = d : digits r
          where (r, d) = x `divMod` 10
    

    Output is

    [153,370,371,407,1634,8208,9474]

    reply permalink

  • Max Burstein - 10 years, 3 months ago

    Nicely done

    reply permalink

  • PyBanana - 10 years, 3 months ago

    Python 2.7 one liner!

    print [i for i in range(10,10000) if sum(int(j) ** len(str(i)) for j in str(i)) == i]
    

    reply permalink

  • Max Burstein - 10 years, 3 months ago

    I love these python one liners. Good stuff

    reply permalink

  • asheehan - 10 years, 3 months ago

    With Ruby

    def isArmstrongNumber(input)
        length = input.to_s.size
        digits = input.to_s.chars.map(&:to_i)
        sum = 0
        digits.each do |digit|
            sum = sum + digit ** length
        end
    
        return sum == input
    end
    
    armstrongNumbers = Array.new
    for i in 10..10000
        if isArmstrongNumber(i)
            armstrongNumbers.push i
        end
    end
    
    puts armstrongNumbers
    

    reply permalink

Content curated by @MaxBurstein