Check Magic Number in Python

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digit sum

What You’ll Learn

A magic number repeatedly reduces by summing its digits until one digit remains — and that digit is 1. This tutorial covers the definition, digital-root link, a live preview, worked Python examples, edge cases, and complexity.

Definition

End at 1

Repeated plain digit sums finish at a single 1.

Classic 19

Magic

19 → 10 → 1.

Digital Root

Root = 1

Magic here means digital root equals 1.

Not Happy

No squares

Happy uses squared digits; magic uses plain sums.

Live Preview

Show steps

Watch each digit-sum reduction in the browser.

O(1) shortcut

n % 9

Digital-root formula after you explain the loops.

Introduction

A magic number (in this interview sense) is a positive integer that reaches 1 when you repeatedly replace it by the sum of its decimal digits. Example: 19 → 10 → 1.

That final single digit is the digital root. Magic here simply means digital root equals 1 — not the same as happy numbers (which square each digit).

Why it matters?

It drills digit peeling and reduction loops — a clean warm-up before (or after) happy / Harshad style problems.

Key Highlights

Reduce to One Digit

Keep summing digits until n ≤ 9.

Magic = Root 1

Final digit must be exactly 1.

Two Styles

Nested loops or digital-root shortcut.

Positive Only

Reject 0 and negatives by convention here.

In short: keep replacing n with the sum of its digits; if you finish at 1, the number is magic.

📝 Problem & Approach

Given a positive integer n, decide whether repeated digit-sum reduction ends at 1.

python
# 19 → 10 → 1   → magic
# 28 → 10 → 1   → magic
# 18 → 9         → not
# 1  → 1         → magic

Inputs & Outputs

ItemTypeDescription
nintPositive integer (reject n ≤ 0).
Return / printbool / textTrue if digital root is 1.

Minimal workflow

Pseudocode
function is_magic(n): // n > 0
    while n > 9:
        s = 0
        while n > 0:
            s += n mod 10
            n = floor(n / 10)
        n = s
    return n == 1

Method comparison

MethodIdeaNotes
Nested loopsDigit sum until one digitInterview default — clear and visual
Digital root1 + (n - 1) % 9O(1); mention after the loop story
Mod 9 checkn % 9 == 1 (n > 0)Same shortcut; handle n%9==0 carefully for root 9

⚡ Quick Reference

GoalPattern
Last digitn % 10
Drop digitn //= 10
One digit-sum passtotal += n % 10
Keep reducingwhile n > 9
Magic testfinal == 1
Shortcut1 + (n - 1) % 9 == 1

📋 Loops vs Shortcut vs Happy

Same digit idea — different stopping rules and formulas.

Nested loops
sum until 1 digit

Beginner-friendly; easy to debug

Digital root
1+(n-1)%9

Constant time after you know the math

Happy numbers
sum of squares

Different problem — do not mix them

Interview tip
loops first

Offer the % 9 shortcut as a follow-up

Context

When This Problem Shows Up

Reach for magic-number checks when digit reduction and digital roots appear.

  1. Interview warm-ups

    Digit loops with a crisp boolean stop condition.

  2. Teaching digital roots

    Same reduction used in divisibility by 9 stories.

  3. Range listing tasks

    Print magic numbers in 1…N for small N.

  4. Beside happy / Harshad

    Contrast plain digit sum vs squared digits vs divisibility.

  5. Positive-only scope

    State that 0 / negatives are out of scope here.

Key benefit: a short digit problem that still opens the door to digital-root theory and O(1) shortcuts.

🔮 Live Preview

Enter a positive safe integer to see each digit-sum reduction step.

Try 19, 18, or 1.

Live result
Press “Run check” to see the digit-sum steps.

Examples Gallery

Three complete Python programs — single check for 19, range 1–50, and a digital-root shortcut. Click View Output to reveal sample console results.

📚 Getting Started

Nested loops that reduce until one digit remains.

Example 1 — Single Value: 19

Uses the classic nested-loop digit-sum reduction with a positive-input guard.

python
def is_magic_number(num: int) -> bool:
    if num <= 0:
        return False
    while num > 9:
        total = 0
        while num > 0:
            total += num % 10
            num //= 10
        num = total
    return num == 1


number = 19
if is_magic_number(number):
    print(f"{number} is a Magic Number.")
else:
    print(f"{number} is not a Magic Number.")

How It Works

The outer loop keeps reducing while the value is multi-digit. The inner loop performs one digit-sum pass. For 19: 1+9=10, then 1+0=1.

⚡ Range Output

Reuse the same helper to filter a beginner interval.

Example 2 — Magic Numbers in [1, 50]

Prints all magic numbers from 1 to 50.

python
def is_magic_number(num: int) -> bool:
    if num <= 0:
        return False
    while num > 9:
        total = 0
        while num > 0:
            total += num % 10
            num //= 10
        num = total
    return num == 1


print("Magic Numbers in the range 1 to 50:")
for i in range(1, 51):
    if is_magic_number(i):
        print(i, end=" ")
print()

How It Works

Numbers congruent to 1 mod 9 (in this positive range) end at digital root 1. The reusable checker keeps the range loop clean.

⚙️ Digital-Root Shortcut

Same verdict in O(1) once you know the formula.

Example 3 — Constant-Time Check

Uses 1 + (n - 1) % 9 and compares to 1.

python
def digital_root(n: int) -> int:
    if n <= 0:
        raise ValueError("n must be positive")
    return 1 + (n - 1) % 9


def is_magic_shortcut(n: int) -> bool:
    if n <= 0:
        return False
    return digital_root(n) == 1


for value in (19, 18, 1, 28):
    label = "magic" if is_magic_shortcut(value) else "not magic"
    print(f"{value}: {label} (root={digital_root(value)})")

How It Works

Digital root collapses all digit-sum iterations into one modulus. In interviews, explain the loop first, then mention this O(1) shortcut.

🧠 How the Algorithm Decides

1

Validate

Reject n ≤ 0 under this page’s convention.

Guard
2

Sum digits

While n > 9, replace n with its digit sum.

Reduce
3

Compare to 1

Magic iff the final single digit is 1.

Verdict
=

Magic or not

Root 1 → yes; otherwise no.

🔎 Worked Walkthrough — n = 19

Trace the digit-sum reductions for the classic magic example.

StepnDigit sumNext
1191 + 910
2101 + 01
31(single digit)stop — magic

Contrast: 18 → 9 stops at 9 → not magic.

Use Cases

Where magic-number checks show up beyond the interview prompt.

1. Interview Warm-Ups

Digit peeling with a clear stop condition.

Example: write is_magic_number(n).

2. Digital-Root Intro

Bridge loops to the % 9 formula.

Example: root of 19 is 1.

3. Range Filters

List magic numbers in a classroom interval.

Example: 1 to 50 list above.

4. Contrast Problems

Separate magic from happy and Harshad.

Example: plain sum vs squares.

5. Divisibility Stories

Digital roots relate to rules for 9.

Example: root 9 ↔ multiple of 9.

6. Debugging Traces

Print each reduction like the live preview.

Example: 19 → 10 → 1.

Pro Tip: say “magic means digital root is 1” before coding the loops.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Clear Rule

    One sentence: digit-sum reduction ends at 1.

  2. 2. Easy to Trace

    19 → 10 → 1 is whiteboard-friendly.

  3. 3. Shortcut Available

    Digital-root formula upgrades the solution later.

  4. 4. Famous Contrasts

    19 vs 18 and magic vs happy catch misconceptions.

Pro Tip: lead with nested loops; offer the digital-root shortcut if asked about optimization.

Usage Tips

Small habits that keep magic-number solutions interview-ready.

  1. 1. Guard Positive n

    Reject n ≤ 0 under this tutorial’s definition.

  2. 2. Stop at One Digit

    Use while n > 9, not an arbitrary iteration count.

  3. 3. Spot-Check 19 and 18

    Magic and not-magic classics catch bugs fast.

  4. 4. Do Not Square Digits

    That is the happy-number map — different problem.

  5. 5. Mention the Shortcut Last

    Explain loops first; then cite digital root.

Pro Tip: 1 is magic because it is already the target single digit — say that when asked about the base case.

Common Pitfalls

Mistakes that commonly break magic-number solutions.

  1. 1. Squaring Digits

    Confusing magic with happy numbers.

    → Sum digits plain — no squares.

  2. 2. Stopping After One Pass

    Checking only the first digit sum (e.g. 19 → 10) and quitting.

    → Keep going until n ≤ 9.

  3. 3. Accepting Zero / Negatives

    This page treats them as not magic.

    → Return False for n ≤ 0.

  4. 4. Wrong Shortcut for Multiples of 9

    Using n % 9 without the digital-root adjustment.

    → Prefer 1 + (n - 1) % 9 for root values.

  5. 5. Mutating Input Carelessly

    Destroying n before you can print the original later.

    → Work on a local copy inside the helper.

Edge Cases

Keep input positive and remember magic is not the same as happy.

Zero

n = 0

This tutorial does not treat 0 as magic.

Negative

Sign convention

Reject negatives unless your task defines otherwise.

Definition

Magic vs happy

Happy uses squared digits; this page uses plain digit sum.

n = 1

Already one digit

Immediately magic — no loop needed.

18

Classic no

18 → 9, final digit is not 1.

Range

1 to 50

Expect 1 10 19 28 37 46.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Digital root. Magic on this page means digital root equals 1.
  • Formula. For n > 0, root = 1 + (n - 1) % 9.
  • Pattern. In small ranges, magic numbers often look like 1, 10, 19, 28, …
  • Not happy. Happy numbers iterate sum of squared digits until 1 or a cycle.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Classify classics

  • 1, 19, 28 → magic
  • 18, 20 → not

2. Match both styles

  • Loops vs digital-root shortcut
  • Assert identical booleans

3. Range 1 to 100

  • List all magic numbers
  • Compare with n % 9 == 1 pattern

4. Print the path

  • Show 19 → 10 → 1
  • Stop when n ≤ 9

Notes

  • Definition: repeated digit sum ends at 1.
  • Code: nested loop approach is beginner-friendly.
  • Optional: digital-root formula provides a constant-time shortcut.
  • Do not confuse with happy numbers (squared digits) or Harshad (divisible by digit sum).

Quick Takeaway: keep summing digits until one remains; magic means that digit is 1.

⏱️ Time and Space Complexity

ApproachTime (single n)Extra space
Repeated digit-sum loopsO((log n)²) practical smallO(1)
Digital-root shortcutO(1)O(1)
Scan [1, N]O(N) checksO(1)

Each digit-sum pass costs O(number of digits); very few passes are needed in practice.

Wrap Up

🎉 Conclusion

Magic numbers (here) are positive integers whose digital root is 1. Implement the nested digit-sum loops first, test 19 and 18, then mention the O(1) digital-root shortcut.

Practice the three examples above, then continue to matrix addition for a 2D array warm-up.

Final digit 1 means magic; 18 → 9 means not — and never square the digits on this page.

💡 Best Practices

✅ Do

  • Reduce with plain digit sums until one digit
  • Test 1, 19, and 18
  • Reject nonpositive inputs
  • Explain loops before the % 9 shortcut
  • Contrast with happy numbers when asked

❌ Don’t

  • Square digits (happy-number habit)
  • Stop after a single digit-sum pass
  • Accept 0 or negatives silently
  • Lead with the shortcut before the definition
  • Confuse digital root 9 with root 0

Key Takeaways

Knowledge Unlocked

Five things to remember about magic numbers

Decide magic the interview-friendly way.

5
Core concepts
Σ 02

Map

Digit sum

Digits
R 03

Root

Digital root = 1

Math
% 04

Shortcut

1+(n-1)%9

O(1)
05

Not happy

No squares

Contrast

❓ Frequently Asked Questions

Repeatedly sum decimal digits until one digit remains; if that digit is 1, the number is magic.
Yes. It is already one digit and equals 1.
No. Happy numbers use sum of squared digits. Magic numbers here use plain digit sums.
This page follows interview convention: use positive integers only.
The final one-digit value is digital root. Magic here means digital root = 1.
Each pass sums digits in O(log n); repeated passes are tiny in practice for standard input sizes.
Yes. For n > 0, digital root is 1 + (n - 1) % 9. Magic iff that equals 1 (equivalently n % 9 == 1).
18 → 9, and the final digit is 9, not 1.

Did you Know? 🔊

Magic-number checks in this page are exactly digital-root checks for root = 1.

Continue to Matrix Addition

Learn how to add two matrices element by element in Python.

Matrix addition 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.

8 people found this page helpful