Placement Prep

Armstrong Number in Python: 3 Easy Programs

Python programs to check Armstrong numbers: while loop, list comprehension, and a range finder. Verified digit-power derivations for 153, 370, 371, 407, and 9474.

By FACE Prep Team 6 min read
armstrong-number python coding-practice placement-prep python-programs digit-extraction

An Armstrong number equals the sum of its digits each raised to the power of its digit count. The four 3-digit Armstrong numbers are 153, 370, 371, and 407.

This problem appears in placement coding rounds at TCS NQT, Infosys InfyTQ, and Wipro aptitude tests. The digit-extraction loop it requires (remainder = temp % 10, shift = temp //= 10) also appears in palindrome checks, digit-sum programs, and number-reversal exercises. Learning one teaches the pattern for all of them.

What is an Armstrong number?

A number with n digits is an Armstrong number if the sum of each digit raised to the power n equals the number itself. The exponent scales with the digit count: 3-digit numbers use power 3, 4-digit numbers use power 4, and 1-digit numbers use power 1.

The formal mathematical term is narcissistic number. The term “Armstrong number” is the standard label in Indian placement prep material; both refer to the same class of integers. The OEIS sequence A005188 lists all narcissistic numbers in base 10: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, and on to numbers with dozens of digits.

Verified examples, arithmetic re-derived from first principles:

  • 153 (3 digits, power 3): 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓
  • 370 (3 digits, power 3): 3³ + 7³ + 0³ = 27 + 343 + 0 = 370 ✓
  • 371 (3 digits, power 3): 3³ + 7³ + 1³ = 27 + 343 + 1 = 371 ✓
  • 407 (3 digits, power 3): 4³ + 0³ + 7³ = 64 + 0 + 343 = 407 ✓
  • 1634 (4 digits, power 4): 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634 ✓
  • 9474 (4 digits, power 4): 9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561 + 256 + 2401 + 256 = 9474 ✓

Edge cases

  • All single-digit numbers (0 through 9) are Armstrong numbers. Any digit raised to the power 1 equals itself, so the check always passes.
  • There are no 2-digit Armstrong numbers. For a 2-digit number with digits a and b, the check computes a² + b². The maximum is 9² + 9² = 81 + 81 = 162, a 3-digit number. No 2-digit combination satisfies the condition.

Python program to check an Armstrong number

Method 1: while loop

The standard approach extracts digits using remainder = temp % 10, raises each to the digit-count power, and accumulates a total.

# Python program to check whether a number is Armstrong or not

number = int(input("Enter a number: "))
total = 0
temp = number
n = len(str(number))   # digit count

while temp != 0:
    digit = temp % 10
    total += digit ** n
    temp //= 10

if total == number:
    print(f"{number} is an Armstrong number")
else:
    print(f"{number} is not an Armstrong number")

How it works:

  • len(str(number)) converts the integer to a string and counts characters, returning the digit count without a separate loop.
  • temp % 10 extracts the rightmost digit. temp //= 10 drops it.
  • digit ** n raises each extracted digit to the digit-count power.
  • The comparison at the end checks whether the accumulated total matches the original.

Sample run for 153:

  • n = 3, total = 0, temp = 153
  • Iteration 1: digit = 3, total = 0 + 27 = 27, temp = 15
  • Iteration 2: digit = 5, total = 27 + 125 = 152, temp = 1
  • Iteration 3: digit = 1, total = 152 + 1 = 153, temp = 0
  • 153 == 153: Armstrong ✓

Sample run for 100:

  • n = 3, total = 0, temp = 100
  • Iteration 1: digit = 0, total = 0 + 0 = 0, temp = 10
  • Iteration 2: digit = 0, total = 0 + 0 = 0, temp = 1
  • Iteration 3: digit = 1, total = 0 + 1 = 1, temp = 0
  • 1 ≠ 100: Not an Armstrong number ✓

The variable name total avoids shadowing Python’s built-in sum() function. The same digit-extraction pattern appears across the Python basic programs collection, making it worth practising until it’s automatic.

Method 2: Pythonic one-liner using sum() and a generator

Python’s sum() built-in with a generator expression compresses the while loop into two lines.

# Pythonic Armstrong number check using sum() and a generator expression

number = int(input("Enter a number: "))
n = len(str(number))
total = sum(int(d) ** n for d in str(number))

if total == number:
    print(f"{number} is an Armstrong number")
else:
    print(f"{number} is not an Armstrong number")

How it works:

  • str(number) iterates character by character over the digits.
  • int(d) converts each character back to an integer.
  • int(d) ** n raises it to the digit-count power.
  • sum(...) adds all the powered digits in one call.

This version is more Pythonic and passes cleanly on most competitive-coding judges. The while-loop version is the expected answer when an interviewer asks you to walk through the execution step by step. The accumulate-and-compare logic here is the same idiom used when summing array elements in Python: process each element, accumulate a running total, compare or return.

Python program to find all Armstrong numbers in a range

To print every Armstrong number between two bounds, wrap the check in a helper function and iterate:

# Python program to find all Armstrong numbers in a given range

def is_armstrong(n):
    if n < 0:
        return False
    digits = len(str(n))
    total = 0
    temp = n
    while temp != 0:
        d = temp % 10
        total += d ** digits
        temp //= 10
    return total == n

lower = int(input("Enter lower bound: "))
upper = int(input("Enter upper bound: "))

print(f"Armstrong numbers from {lower} to {upper}:")
for num in range(lower, upper + 1):
    if is_armstrong(num):
        print(num, end=" ")
print()

Output for range 100 to 500: 153 370 371 407

Output for range 1000 to 9999: 1634 8208 9474

The is_armstrong() function checks n < 0 as a guard; negative inputs never appear in placement tests but defensive coding is a good habit. The end=" " argument on print() places all results on one line separated by spaces, matching the expected output format on most coding judges.

Naive loop vs. precomputed set

The range-finder above uses the naive approach: for each number in the range, run the full digit-power check. The time cost is O(R × d), where R is the range width and d is the average digit count.

For a range like 1 to 9999:

  • R × d ≈ 9999 × 3 ≈ 30,000 operations total
  • Fast enough for any placement coding test

A precomputed set is also valid: there are exactly 88 narcissistic numbers in base 10, from single-digit numbers up to a 39-digit number. Storing them in a Python set and using if n in armstrong_set gives O(1) lookup. For placement-round inputs, both approaches are acceptably fast. The naive loop is preferable in tests because it requires no hardcoded data and demonstrates understanding of the algorithm.

Armstrong number in C, C++, and Java

The algorithm is identical across languages. The main difference is how each language counts digits before the extraction loop:

LanguageDigit count methodpow() note
Pythonlen(str(number))** returns exact integer
CWhile loop: divide by 10 until zeropow() returns double; cast to int
C++While loop: same as CSame cast required
JavaString.valueOf(n).length()Math.pow() returns double; cast to int

In C and C++, floating-point precision in pow(rem, digits) can cause off-by-one errors for large inputs if the result is not cast to int. Python’s ** operator is exact for integer operands, which removes this concern.

For complete C, C++, and Java implementations with sample runs and edge-case notes, see the companion article Armstrong Number Check: Python, C, C++ and Java Programs.

Time and space complexity

MetricValueNotes
Time: single checkO(d)One pass to count digits, one pass to sum digit powers
Space: single checkO(1)Fixed set of integer variables
Time: range finderO(R × d)R = range width, d = average digit count
Digit-count passO(d)Divide by 10 until zero; len(str(n)) does the same
Digit-power passO(d)One modulo + power operation per digit

For a 9-digit input, d = 9, so the single-check runs in at most 18 operations. For the range 1 to 9999, the range finder completes in well under a second on any modern machine. Both are effectively constant-time for all practical placement test inputs.

Using Python function discipline on bigger problems

The is_armstrong() function above does one thing clearly: take a single integer, compute a digit-power sum, return a boolean. No side effects, no print statements inside the function, no global state. That single-purpose design is the same pattern you write when building any utility function in a real project.

The same discipline applies when you start calling AI APIs: write a function that takes input, calls the endpoint, parses the response, and returns a clean result. TinkerLLM at ₹299 is where FACE Prep readers who have mastered these building-block Python programs go to apply that same function-call pattern to live LLM projects they can add to a placement portfolio.

Primary sources

Frequently asked questions

What is an Armstrong number?

An Armstrong number of n digits equals the sum of each digit raised to the power n. For 153 (a 3-digit number), the check is 1 cubed + 5 cubed + 3 cubed = 1 + 125 + 27 = 153. The mathematical term is narcissistic number; both refer to the same class of integers.

Is 9474 an Armstrong number?

Yes. 9474 is a 4-digit number, so the exponent is 4. Verification: 9 to the 4th + 4 to the 4th + 7 to the 4th + 4 to the 4th = 6561 + 256 + 2401 + 256 = 9474. The sum equals the original number, confirming 9474 is a 4-digit Armstrong number.

Why is there no 2-digit Armstrong number?

For a 2-digit number with digits a and b, the Armstrong check computes a squared + b squared. The maximum possible value is 9 squared + 9 squared = 81 + 81 = 162, which is a 3-digit number. No 2-digit number ab satisfies that equation, so no 2-digit Armstrong numbers exist.

How many Armstrong numbers are there from 1 to 999?

There are 13: the nine single-digit numbers 1 through 9 (where any digit raised to the power 1 equals itself) and the four 3-digit numbers 153, 370, 371, and 407.

What is the time complexity of the Armstrong number check?

O(d) where d is the digit count of the input. The algorithm makes one pass to count digits and one pass to extract and power each digit. For typical placement-round inputs up to 9 digits, this is at most 18 operations.

How do I find all Armstrong numbers in a range in Python?

Write a helper is_armstrong(n) that returns True if n is Armstrong. Then loop: for num in range(lower, upper + 1), print num if is_armstrong(num) returns True. For the range 100 to 500, the output is 153, 370, 371, and 407.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF