Search code examples
pythonpython-3.xpython-2.7numbers

Checking whether a 3 digit number is an armstrong number and returning boolean by describing a function in python3


I tried as input method but unable to return a boolean value as the function's output. Given a 3 digit number, check whether it is an angstrom number or not.


Solution

  • An Amstrong number is a number where the sum of cubes of the digits are equal to the number.

    If your input is taken as a string, you can iterate over the digits since strings are iterable in python:

    def is_armstrong(num):
        return str(sum(int(digit)**3 for digit in num)) == num
    

    If you already have the input as a number, you can "iterate" over the digits by taking modolu 10 of the number in each iteration to extract the last digit:

    def is_armstrong(num):
        n = num
        s = 0
        while n > 0:
            digit = n % 10
            s += digit ** 3
            n //= 10
    
        return s == num