Python Practice › Loop Programs › Program 36

Armstrong numbers from 1 to n

MediumLoop Programs · 36 of 90

Write a Python program to print all Armstrong numbers from 1 to n.

Advertisement
Input
n = 10000
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]

Approach

  1. Apply the Armstrong test to every number.

Solution

Python
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.

More loop programs

← All 90 Loop Programs

Leave a Comment