Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to 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 = 27 + 343 + 0 = 370.
Algorithm Steps
The algorithm to check for an Armstrong number follows these steps ?
- 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
Here are two different approaches to find Armstrong numbers within a given range ?
Method 1: Using Double Star Operator
The program below uses the double star operator (**) to calculate the power of the digits ?
for num in range(50, 1000):
original = num
total = 0
n = len(str(num))
while num > 0:
digit = num % 10
total += digit ** n
num //= 10
if total == original:
print(original)
The output of the above code is ?
153 370 371 407
Method 2: Using pow() Function
This optimized approach uses the built−in pow() function and defines a reusable function ?
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 output of the above code is ?
1634 8208 9474
Finding the First N Armstrong Numbers
This example finds and prints the first 10 Armstrong numbers ?
def is_armstrong(num):
n = len(str(num))
total = sum(int(digit) ** n for digit in str(num))
return total == num
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 of the above code is ?
1 2 3 4 5 6 7 8 9 153
Comparison
| Method | Function | Best For |
|---|---|---|
| Double Star Operator | ** | Simple power calculations |
| pow() Function | pow(base, exp) | More readable code |
| Generator Expression | sum(... for ...) | Concise and efficient |
Conclusion
Armstrong numbers can be efficiently found using either the ** operator or pow() function. The generator expression approach with sum() provides the most concise and readable solution for checking Armstrong numbers.
