Check Armstrong Number in Python

Beginner
⏱️ 12 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digits & powers

What You’ll Learn

An Armstrong number equals the sum of its digits each raised to the power of the digit count. This tutorial covers the definition, a live preview, algorithm steps, worked Python examples, edge cases, and complexity.

Definition

Sum = n

n is Armstrong when each digit raised to power k (digit count) adds up to n.

Count Digits

Find k

Use len(str(n)) or a loop dividing by 10 — k is the exponent for every digit.

Digit Loop

% 10 // 10

Extract digits with modulo, add digit ** k, then compare the total to n.

Classic 153

1³+5³+3³

The schoolbook example: 1³ + 5³ + 3³ = 153 — your golden test.

Live Preview

Try any n

Type a number and see each digit-power term plus the final verdict.

O(log n)

Complexity

One check walks each digit once; extra space stays O(1).

Introduction

An Armstrong number (also called a narcissistic number) is a positive integer that equals the sum of its digits each raised to the power of how many digits it has.

For a number n with k digits, compute d1k + d2k + … + dkk. If that sum is n, the number is Armstrong. The classic classroom example is 153: 1³ + 5³ + 3³ = 153.

Why it matters?

It trains digit extraction, counting, and integer powers — three skills that show up constantly in interview number problems.

Key Highlights

Same Exponent

Every digit uses power k — the digit count of n.

1–9 Always Work

Single-digit numbers satisfy d¹ = d, so they are Armstrong.

Keep Original n

Extract digits from a temp copy so you can still compare to n.

Integer Powers

Use ** (or integer loops) — avoid float rounding traps.

In short: count digits k, sum each digitk, and check whether that sum equals the original number.

📝 Problem & Approach

Given a positive integer n, decide whether it is an Armstrong number.

python
# Example: n = 153 (k = 3 digits)
# 1**3 + 5**3 + 3**3 = 1 + 125 + 27 = 153
# sum == n  → Armstrong

Inputs & Outputs

ItemTypeDescription
nintPositive integer to test (this tutorial returns false for n <= 0).
Return / printbool / textTrue / message when the digit-power sum equals n.

Minimal workflow

Pseudocode
function isArmstrong(n):
    if n <= 0:
        return false
    k = number of digits in n
    sum = 0
    for each digit d in n:
        sum = sum + d^k
    return sum == n

Method comparison

MethodIdeaNotes
Arithmetic loop% 10 / // 10 with digit ** kInterview classic; O(1) extra space
String digitsIterate characters of str(n)Very readable; same O(log n) time

⚡ Quick Reference

GoalPattern
Digit count kpower = len(str(n))
Next digitdigit = temp % 10
Drop last digittemp //= 10
Add powered digittotal += digit ** power
Armstrong testtotal == n
3-digit classics153, 370, 371, 407

📋 Arithmetic vs String vs Fixed Cube

All can detect Armstrong numbers — generality differs.

Arithmetic
% 10 // 10

Best default for interviews; no string conversion

String walk
for ch in str(n)

Short and clear; fine when readability wins

Always ^3
fixed cube

Only correct for 3-digit numbers — avoid as general solution

Interview tip
use k digits

Always set the exponent from the digit count

Context

When This Problem Shows Up

Reach for Armstrong drills when digit loops and powers matter.

  1. Interview warm-ups

    Quick check of modulo loops, exponents, and equality returns.

  2. School / college labs

    Classic first program after learning loops and %.

  3. Range printing tasks

    “Print all Armstrong numbers from 1 to N” reuses one helper.

  4. Teaching digit math

    Makes % 10 and // 10 feel concrete with a famous example.

  5. Not for huge digit counts alone

    Very large k makes powers enormous — discuss constraints in the prompt.

Key benefit: one short problem that covers digits, powers, helpers, and O(log n) reasoning.

🔮 Live Preview

Enter a positive integer to see each digit-power term and the verdict.

Use integers n ≥ 1 (preview capped at 999999999).

Live result
Press "Run check" to see details.

Examples Gallery

Three complete Python programs — check one number, print a range, and a string-based variant. Click View Output to reveal sample console results.

📚 Getting Started

Arithmetic digit extraction — the interview default.

Example 1 — Check a Single Number

Count digits, sum digit ** power, then compare with the original value.

python
def is_armstrong(n: int) -> bool:
    if n <= 0:
        return False
    power = len(str(n))
    total = 0
    temp = n
    while temp > 0:
        digit = temp % 10
        total += digit ** power
        temp //= 10
    return total == n


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

How It Works

Guard non-positive inputs, compute power once, then walk digits via temp so n stays intact for the final comparison.

📈 Practical Patterns

Reuse the helper across a closed range.

Example 2 — Armstrong Numbers in a Range

Loop from start to end and print every value that passes the check.

python
def is_armstrong(n: int) -> bool:
    if n <= 0:
        return False
    power = len(str(n))
    total = 0
    temp = n
    while temp > 0:
        digit = temp % 10
        total += digit ** power
        temp //= 10
    return total == n


start, end = 1, 200
print(f"Armstrong numbers in the range {start} to {end}:")
for value in range(start, end + 1):
    if is_armstrong(value):
        print(value, end=" ")

How It Works

Single-digit values appear first (each is Armstrong), then 153 is the only other hit in 1…200. The helper stays pure; the loop only decides what to print.

📄 Readable Variant

Same math with string iteration.

Example 3 — String-Based Digit Walk

Convert to a string, raise each character digit to power len(s), and compare.

python
def is_armstrong(n: int) -> bool:
    if n <= 0:
        return False
    s = str(n)
    power = len(s)
    total = sum(int(ch) ** power for ch in s)
    return total == n


print(is_armstrong(153))
print(is_armstrong(123))

How It Works

len(s) is k; each character becomes an int and is raised to that power. 153 passes; 123 sums to 36 and fails.

🧠 How the Algorithm Decides

1

Validate n

If n <= 0, return false for this tutorial’s positive-integer definition.

Guard
2

Count digits

Set k (power) from the number of digits in n.

Exponent
3

Sum digit powers

Extract each digit and add digit ** k into a running total.

Accumulate
=

Compare to n

Return true only when the powered digit sum equals the original number.

🔎 Worked Walkthrough — n = 153

Trace the arithmetic method. Digit count k = 3. Start with temp = 153 and total = 0.

tempDigitAddtotal
15333**3 = 2727
1555**3 = 125152
111**3 = 1153

Final check: 153 == 153Armstrong.

Use Cases

Where Armstrong checks show up beyond the interview prompt.

1. Interview Coding

Standard warm-up for digit loops and powers.

Example: write is_armstrong(n).

2. Teaching Modulo

Makes % 10 and // 10 memorable with 153.

Example: chalkboard digit peel.

3. Range Filters

Print or count Armstrong numbers inside bounds.

Example: all hits from 1 to 1000.

4. Related Digit Problems

Skills transfer to Armstrong-like and digit-sum variants.

Example: Disarium / automorphic follow-ups.

5. Complexity Practice

Argue O(log n) from digit count convincingly.

Example: “how many loop iterations?”

6. Integer vs Float Talk

Shows why exact integer powers matter for equality.

Example: reject math.pow floats.

Pro Tip: keep one is_armstrong helper and reuse it for single checks and range printers — less duplicated digit logic.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Definition Maps Cleanly

    Count digits, sum powers, compare — almost no translation gap.

  2. 2. Works for Any Digit Length

    Using k from the digit count handles 1-digit through multi-digit cases.

  3. 3. Tiny Extra Memory

    A few integers suffice — O(1) extra space.

  4. 4. Easy Self-Checks

    153 / 370 / 371 / 407 and 123 give instant confidence.

Pro Tip: say “exponent equals digit count” out loud before coding — it stops the fixed-cube mistake.

Usage Tips

Small habits that keep Armstrong code interview-ready.

  1. 1. Copy Before Peeling Digits

    Use temp = n so the original value survives for comparison.

  2. 2. Compute Power Once

    Count digits before the sum loop — do not recalculate k each iteration.

  3. 3. Prefer Integer **

    Stay exact; floating powers can spoil equality on larger inputs.

  4. 4. Test Positives and Negatives

    Assert True on 153/370 and False on 123 before moving on.

  5. 5. Clarify 0 Policy

    Ask whether 0 counts; this page treats only positive integers.

Pro Tip: dry-run 153 on paper once — it catches off-by-one digit-count bugs faster than guessing.

Common Pitfalls

Mistakes that commonly break Armstrong solutions.

  1. 1. Always Cubing Digits

    Hard-coding ^3 fails for 1-digit and multi-digit cases beyond 3.

    → Set the exponent from the digit count every time.

  2. 2. Destroying the Original n

    Looping on n itself leaves nothing to compare against.

    → Peel digits from a temp copy.

  3. 3. Using Float Powers

    math.pow can introduce rounding that breaks equality.

    → Prefer integer **.

  4. 4. Skipping Single Digits

    Some students assume only 3-digit examples count.

    → Remember 1–9 are Armstrong under the standard definition.

  5. 5. Ignoring Non-Positive Inputs

    Negative or zero values need an explicit policy.

    → Return false early for n <= 0 in this tutorial.

Edge Cases

Check these inputs before calling the solution done.

n <= 0

Return false

This tutorial uses positive integers only.

1–9

All Armstrong

Single-digit values satisfy d¹ = d.

153

Golden test

Must return true for any correct implementation.

123

Negative case

Sum is 36 — must return false.

Original n

Keep a copy

Extract digits from temp, compare against n.

Large n

Big powers

Python ints stay exact; watch time for huge ranges.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • 3-digit set. The only 3-digit Armstrong numbers are 153, 370, 371, and 407.
  • Narcissistic. In number theory, these are often called narcissistic numbers of order k.
  • Order matters. The exponent is the digit count of that specific n — not a global constant.
  • Rare for large k. As digit length grows, Armstrong numbers become sparse.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify the 3-digit set

  • Confirm 153, 370, 371, 407
  • Reject nearby values like 152 and 372

2. Count in a range

  • How many Armstrong numbers are in 1…1000?
  • Reuse is_armstrong

3. No str allowed

  • Count digits with a divide-by-10 loop
  • Same answer as len(str(n))

4. Print power terms

  • For debugging, print each d^k like the live preview
  • Great for explaining interviews aloud

Notes

  • Exponent = digit count. That single rule separates Armstrong from casual “sum of cubes” shortcuts.
  • Preserve the original n while extracting digits — compare at the end.
  • 1 through 9 are valid Armstrong numbers under this definition.
  • State O(log n) time and O(1) extra space when asked about complexity.

Quick Takeaway: sum each digit raised to the digit-count power; if that equals n, the number is Armstrong.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Single checkO(log n)O(1)
String-style checkO(log n)O(log n) for the string
Range 1…Uabout O(U log U)O(1)
Wrap Up

🎉 Conclusion

Armstrong numbers are a clean digit-power exercise: find k, sum each digitk, and compare with n. Master the arithmetic loop first, then the string variant when you want shorter code.

Practice the three examples above, then continue to automorphic numbers for another classic digit-pattern check.

Never hard-code cubes for all cases, never overwrite n while peeling digits, and always verify 153.

💡 Best Practices

✅ Do

  • Set the exponent from the digit count
  • Use a temp variable for digit extraction
  • Prefer integer ** powers
  • Test 153, 370, 1, and 123
  • State O(log n) time when asked

❌ Don’t

  • Hard-code power 3 for every n
  • Mutate n before comparing
  • Rely on floating-point powers
  • Forget that 1–9 are Armstrong
  • Skip the n <= 0 guard

Key Takeaways

Knowledge Unlocked

Five things to remember about Armstrong numbers

Check digit powers the interview-friendly way.

5
Core concepts
k 02

Exponent

k = digit count

Math
% 03

Digits

% 10 and // 10

Code
153 04

Classic

1³+5³+3³

Example
O 05

Complexity

O(log n) time

Analysis

❓ Frequently Asked Questions

A positive integer n is an Armstrong number if it equals the sum of its digits, where each digit is raised to the power of total digits in n. Example: 153 = 1^3 + 5^3 + 3^3.
Yes. For a one-digit number d, we have d^1 = d, so 1 to 9 are Armstrong numbers.
Some definitions include 0. In this tutorial, we check positive integers only, so n <= 0 returns false.
Integer power avoids rounding issues and keeps equality checks exact.
The same value k for all digits — where k is the count of digits in n. Do not use a fixed cube unless you only care about 3-digit cases.
For one number, complexity is O(log n) because we process each digit a constant number of times.
Yes. Loop from low to high and test each value with the same helper function.
Yes in common programming tutorials — both mean the digit-power sum with exponent equal to the digit count equals the number.

Did you Know? 🔊

For 3-digit numbers, the Armstrong values are 153, 370, 371, and 407.

Continue to Automorphic Number

Learn how to check whether a number’s square ends with the number itself.

Automorphic number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful