Print Narcissistic Armstrong Numbers with Python



A narcissistic number (also known as an Armstrong number) is a number that equals the sum of its digits, each raised to the power of the number of digits. For example, 370 - 33+73+03 = 370. The algorithm to check for an Armstrong number is as follows -

  • Determine the number of digits for the mentioned number.
  • Extract each digit and calculate the power of that digit with the exponent equal to the number of digits.
  • Calculate the sum of the power.
  • Compare with the original number.

Finding Armstrong Numbers in a Range

The two examples below illustrate how to find Armstrong numbers in a given range in two different ways -

Example

The program below is the brute force solution, which uses the double star operator(**) to calculate the power of the digits.

for num in range(50, 1000):
   original = num
   sum = 0
   n = len(str(num))
 
   while num > 0:
      digit = num % 10
      sum += digit ** n
      num //= 10
 
   if sum == original:
      print(original)

The above code returns the Armstrong numbers in the range 50 to 1000 as given below -

153
370
371
407

Example

In comparison with the above example, this is an optimized approach where we use the pow() function to calculate the power of the digits.

We also define the is_armstrong() function to print Armstrong numbers that can be called anywhere in the code. The pow(base,exp) function is a built-in function in Python that is used to calculate the power of a number.

def is_armstrong(num):
   digits = str(num)
   n = len(digits)
   total = sum(pow(int(d), n) for d in digits)
   return total == num

# Print Armstrong numbers in the given range
for number in range(700, 10000):  
   if is_armstrong(number):
      print(number)

The above code returns the Armstrong numbers in the range 700 to 10000 as given below -

1634
8208
9474

Finding the First "N" Armstrong Numbers

The example program below will allow you to calculate the first 10 Armstrong numbers -

# Function to check if a number is an Armstrong number
def is_armstrong(num):
    n = len(str(num))
    total = sum(int(digit) ** n for digit in str(num))
    return total == num

# Function to find and print the first n Armstrong numbers
def first_n_armstrong(n):
    count = 0
    num = 1
    while count < n:
        if is_armstrong(num):
            print(num)
            count += 1
        num += 1  
first_n_armstrong(10)

The output returned by the above code is as follows -

1
2
3
4
5
6
7
8
9
153
Updated on: 2025-05-16T19:37:20+05:30

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements