Python - Find Armstrong Numbers within Interval

Armstrong number is a number that is equal to the sum of cubes of its digits.
For example 0,1,153,371 and 407 are the Armstrong numbers.

Let's understand how 153 is an Armstrong number.

    153 = (1*1*1) + (5*5*5) + (3*3*3), 
    
    where

    (1*1*1) = 1
    (5*5*5) = 125
    (3*3*3) = 27
    
    Hence, 1+ 125 + 27 = 153

General formula to find the armstrong number

 
      abcde......nth = an + bn + cn + dn + en +......nthn
                    

In this program, you will learn how to find the Armstrong numbers within in the interval.


Program Code



    # Enter the lower and upper numbers
    lower = int(input('Enter the  start number : '))
    upper = int(input('Enter the  end number : '))
    
    for num in range(lower, upper +1):
        # Find the number of digits
        order = len(str(num))
    
        # Initialize sum
        sum = 0
    
        # Find the sum of the cube of each digit
    
        temp = num
        while temp > 0:
            digit = temp % 10
            sum += digit ** order
            temp = temp // 10
    
        # Display the result
        if num == sum:
            print(num)

Output



    Enter the  start number : 10
    Enter the  end number : 2000
    153
    370
    371
    407
    1634

In this program, we have used for loop to iterate from variable lower to upper. Find the order (number of digits) of the given number. Also, we have initialized the sum to 0 and obtain each digit number by using the modules operator %. The remainder of a number is the last digit of that number when it is divided by 10. We will calculate the digit exponent value and sum of them.

Finally, we compare the sum with the original number and consider it is Armstrong number and display if they are equal.

You can change the range and test out by chaning the variables lower and upper.



The following topics can be useful to understand this program.



Related Tutorials