Python Practice › Loop Programs › Program 36
Armstrong numbers from 1 to n
Write a Python program to print all Armstrong numbers from 1 to n.
Input
n = 10000
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]
Approach
- Apply the Armstrong test to every number.
Solution
def is_armstrong(n): digits = str(n) return n == sum(int(d) ** len(digits) for d in digits) print([n for n in range(1, 10001) if is_armstrong(n)])Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]
Line by line
Line 3
The sum of the powered digits is compared with the number itself.
Learn the concept
New to this topic? Read the lesson, then come back.