Python Tutorials

Python Programs

Python Find Armstrong Numbers in an Interval


Python Find Armstrong Numbers in an Interval

In this tutorial, we will learn how to find all Armstrong numbers in a given interval in Python. We will cover the definition of an Armstrong number and implement a function to identify Armstrong numbers within a specified range.


What is an Armstrong Number

An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.


Syntax

The syntax to find Armstrong numbers in an interval in Python is:

def is_armstrong(number):
    digits = [int(d) for d in str(number)]
    power = len(digits)
    total = sum(d ** power for d in digits)
    return total == number

for num in range(start, end + 1):
    if is_armstrong(num):
        print(num)


Finding Armstrong numbers in an interval

We can create a function to check if a number is an Armstrong number and use it to find all Armstrong numbers within a specified range.

For example,

  1. Define a function named is_armstrong that takes one parameter number.
  2. Convert the number to a string and then to a list of its digits.
  3. Determine the number of digits in the number.
  4. Compute the sum of each digit raised to the power of the number of digits.
  5. Return True if the computed sum equals the original number, otherwise return False.
  6. Declare the start and end values for the interval.
  7. Use a for loop to iterate through the numbers in the interval.
  8. Use the is_armstrong function to check if the current number is an Armstrong number. If true, print the number.

Python Program

def is_armstrong(number):
    digits = [int(d) for d in str(number)]
    power = len(digits)
    total = sum(d ** power for d in digits)
    return total == number

# Define the interval
start = 100
end = 1000

# Print all Armstrong numbers in the interval
for num in range(start, end + 1):
    if is_armstrong(num):
        print(num)

Output

153
370
371
407