Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Armstrong Numbers in Range

Find Armstrong numbers from one through one thousand with Python. Students count each candidate's digits, reset its working copy, and use that count as the power.

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

In this one

  • Use candidate-specific powers
  • Reset a consumed copy
  • Include single-digit solutions

How it works

  1. 1

    Count the current candidate's digits.

  2. 2

    Restore temp and sum digit ** count.

  3. 3

    Print candidates equal to that sum.

Edge cases

Are single digits included?

Are single digits included?

Yes. Each equals itself to power one.

Why is zero absent?

Why is zero absent?

The search starts at one, not because zero fails the definition.

What's going on

Each candidate gets its own digit count. The second digit loop sums digit ** count after temp has been restored.

All one-digit candidates pass because their power is one; familiar three-digit examples include 153, 370, 371, and 407. Zero satisfies the general mathematical rule but is outside this loop's range. One thousand is tested with power four and does not qualify.

Are single digits included? Yes. Each equals itself to power one.

Why is zero absent? The search starts at one, not because zero fails the definition.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why reset temp?

Pick an answer to check it.

Question 2

Are single digits included?

Pick an answer to check it.

Questions people ask

Are single digits included?

Yes. Each equals itself to power one.

Why is zero absent?

The search starts at one, not because zero fails the definition.

Why reset temp?

The counting loop has consumed the first copy.