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

Armstrong Number Check

Check Armstrong numbers using the number of digits as the power. Students trace two Python digit loops and distinguish exponentiation from bitwise XOR.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 5 of 14
armstrong-number-check.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Count digits
5temp = abs(num)
6count = 0
7while temp > 0:
8 count += 1
9 temp //= 10
10
11# Calculate sum of digits raised to power
12temp = abs(num)
13armstrong_sum = 0
14while temp > 0:
15 digit = temp % 10
16 armstrong_sum += digit ** count
17 temp //= 10
18
19# Check
20if abs(num) == armstrong_sum:
21 print("Armstrong number")
22else:
23 print("Not an Armstrong number")

Output

Enter a number: 153
Armstrong number

Enter a number: 123
Not an Armstrong number

In this one

  • Count before powering
  • Reset consumed state
  • Use ** for powers

How it works

  1. 1

    Count digits in the first temp scan.

  2. 2

    Reset temp and sum digit ** count.

  3. 3

    Compare that sum with the original magnitude.

Edge cases

Do single digits pass?

Do single digits pass?

Yes. Each positive single digit equals itself raised to power one.

What does zero do?

What does zero do?

Both loops are skipped and zero equals the zero total, so it passes.

What's going on

An Armstrong check adds each digit raised to the total digit count. The first loop counts positions, then temp is reset so a second loop can read them again.

For 153, the test computes 1 cubed + 5 cubed + 3 cubed = 153. ** means power. The code compares magnitudes, so it also accepts negative inputs with an Armstrong magnitude. Zero is accepted by equality after both loops are skipped.

Do single digits pass? Yes. Each positive single digit equals itself raised to power one.

What does zero do? Both loops are skipped and zero equals the zero total, so it passes.

Quiz

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

Question 1

Why reset temp between loops?

Pick an answer to check it.

Question 2

Do single digits pass?

Pick an answer to check it.

Questions people ask

Do single digits pass?

Yes. Each positive single digit equals itself raised to power one.

What does zero do?

Both loops are skipped and zero equals the zero total, so it passes.

Why reset temp between loops?

The first loop has consumed it.