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.
1# Take number2num = int(input("Enter a number: "))34# Count digits5temp = abs(num)6count = 07while temp > 0:8 count += 19 temp //= 101011# Calculate sum of digits raised to power12temp = abs(num)13armstrong_sum = 014while temp > 0:15 digit = temp % 1016 armstrong_sum += digit ** count17 temp //= 101819# Check20if 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
Count digits in the first temp scan.
- 2
Reset temp and sum digit ** count.
- 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.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum