Armstrong Numbers in Range

Find Armstrong numbers in range 1-1000.

AdvancedPhase 6 - Category 1: Number LogicExample 4 of 10
armstrong-numbers-in-range.py
1# Find Armstrong numbers
2print("Armstrong numbers 1-1000:")
3
4for num in range(1, 1001):
5 # Count digits
6 temp = num
7 count = 0
8 while temp > 0:
9 count += 1
10 temp //= 10
11
12 # Calculate sum
13 temp = num
14 armstrong_sum = 0
15 while temp > 0:
16 digit = temp % 10
17 armstrong_sum += digit ** count
18 temp //= 10
19
20 if armstrong_sum == num:
21 print(num, end=" ")
22print()

Output

Armstrong numbers 1-1000:
1 2 3 4 5 6 7 8 9 153 370 371 407

What's going on

Check each number for Armstrong property.

Key Concepts:

Count digits
Calculate sum of digits^count
Compare with number