Check Magic Number in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Digit sum

What you’ll learn

  • The usual interview definition: repeated decimal digit sum until one digit remains; magic means that digit is 1.
  • A compact isMagicNumber function and console.log drivers matching classic examples (19, range 1–50).
  • A browser live preview, pseudocode, complexity notes, try-it editors (target="_blank"), and how this ties to the digital root.

Overview

This walkthrough implements the popular schoolbook rule: keep adding decimal digits until the value is a single digit; if that digit is 1, the original number is called a magic number here.

Two programs

A single-value check for 19 and a range listing for 1 to 50.

Live preview

Shows each digit-sum step in the browser before you copy code into Node or DevTools.

Tables & rigor

I/O samples, edge cases (zero/negative/safe integers), and complexity for interviews.

Prerequisites

Loops, integer division with Math.floor, and the remainder operator %.

  • console.log, Number.isSafeInteger for validation in the live widget.
  • Extracting digits with n % 10 and Math.floor(n / 10).

What is a magic number?

Start from a positive integer. Repeatedly replace it by the sum of its decimal digits until you hold a single digit. If that digit is 1, the starting value is a magic number (for this tutorial).

For 19: 1 + 9 = 10, then 1 + 0 = 1—so 19 is magic.

Magic final digit 1
Not magic final digit 2–9

Repeated digit sum

Let S(n) be the sum of the base-10 digits of n (for n > 0). Define T(n) by repeatedly applying S until the argument is in {1,…,9}. That fixed value is the digital root (for our inputs). The number is magic iff T(n) = 1.

Quick contrast

181+8 = 9, stops at 9, so it is not magic under this definition. 28101, so it is magic.

Intuition and examples

19 Magic
Steps
19 → 10 → 1
28 Magic
Steps
28 → 10 → 1
18 Not magic
Steps
18 → 9 (stops)

Takeaway: you only care about the last single digit produced by the chain, not how many steps it took.

Live preview

Enter a positive integer to watch the same digit-sum chain as the JavaScript examples. Values must fit JavaScript safe integers for this widget.

Try 19, 18, or 1. Avoid negatives.

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

Algorithm

Goal: return true iff repeated digit summation ends at 1.

Validate

For the programs below, assume n > 0. (Zero is not treated as magic.) Use Number.isSafeInteger(n) when reading user input.

Reduce

While n > 9, replace n by the sum of its decimal digits using % 10 and Math.floor(n / 10).

Decide

After the loop, n is one digit. It is magic iff n === 1.

📜 Pseudocode

Pseudocode
function digit_sum(n):   // n >= 0
    s ← 0
    while n > 0:
        s ← s + (n mod 10)
        n ← floor(n / 10)
    return s

function is_magic(n):   // assume n > 0
    while n > 9:
        n ← digit_sum(n)
    return (n = 1)
1

Check a single number (program with explanation)

Uses 19 as in the classic walkthrough. The inner loops match the reference: outer loop continues until the value is one digit; inner loop computes the digit sum.

JavaScript
function isMagicNumber(num) {
  while (num > 9) {
    let sum = 0;

    while (num > 0) {
      sum += num % 10;
      num = Math.floor(num / 10);
    }

    num = sum;
  }

  return num === 1;
}

const number = 19;

if (isMagicNumber(number)) {
  console.log(number + " is a Magic Number.");
} else {
  console.log(number + " is not a Magic Number.");
}
Try it Yourself

Explanation

The outer while (num > 9) keeps collapsing the value; the inner while is one pass of digit summation. When num is a single digit, compare it to 1.

while (num > 9)

Stop when digital root is reached. Any positive integer eventually lands in 1..9 under repeated digit sums.

return num === 1;

Magic test. Only the final single digit matters for this definition.

2

Magic numbers in a range (program with explanation)

Prints every magic number from 1 through 50 on one line after a banner, matching the usual sample output.

JavaScript
function isMagicNumber(num) {
  while (num > 9) {
    let sum = 0;
    while (num > 0) {
      sum += num % 10;
      num = Math.floor(num / 10);
    }
    num = sum;
  }
  return num === 1;
}

console.log("Magic Numbers in the range 1 to 50:");

const parts = [];
for (let i = 1; i <= 50; i++) {
  if (isMagicNumber(i)) {
    parts.push(String(i));
  }
}
console.log(parts.join(" ") + " ");
Try it Yourself

Explanation

Reuse isMagicNumber for each i. Adjust 50 or the start index for other intervals.

Optimization notes

Digital root formula. For n > 0, one form of the digital root is 1 + ((n - 1) % 9), which yields 1 exactly for magic numbers in this sense (with the usual 9 special case handled in closed-form variants). Many teams still prefer the explicit loop in interviews because it is easier to trace.

Interview: implement the loop first; mention the closed form only if asked for speed or follow-up math.

❓ FAQ

A positive integer is magic if you repeatedly replace it by the sum of its decimal digits until one digit remains, and that digit is 1. Example: 19 → 10 → 1, so 19 is magic.
Yes. It is already a single digit and equals 1, so the process stops immediately with a magic result.
No. Happy numbers use the sum of squared digits. Magic numbers in this tutorial only sum digits (no squares).
This page follows the usual interview convention: test only nonnegative inputs; the sample programs assume a positive integer.
The final single digit after repeated digit sums is the digital root (for base 10). Here &ldquo;magic&rdquo; means digital root equals 1.
Each digit-sum pass is O(log n) digits; there are O(log n) passes until the value is under 10, so the overall check is O((log n)²) for values that fit in a Number—effectively tiny for safe integers.

🔄 Input / output examples

For the single-number program, typical console.log lines look like this (you can bind number from prompt or CLI args in Node if you prefer interactive input):

Test numberTypical line printed
1919 is a Magic Number.
1818 is not a Magic Number.
11 is a Magic Number.
2828 is a Magic Number.

Edge cases and pitfalls

Clarify requirements before you code: sign, zero, safe integers, and whether “magic” uses digit sum or sum of squares.

Zero

n = 0

The inner digit loop yields sum 0; the reference logic does not classify 0 as magic. If your assignment requires nonnegative input, state that in comments.

Sign

Negative values

Digit extraction on negatives needs a clear rule (often: reject, or use absolute value). The samples here stay strictly positive.

Naming

Other “magic” meanings

Compilers also use “magic number” for unexplained literals in code—unrelated to this math exercise.

⏱️ Time and space complexity

ApproachTime (single n)Extra space
Repeated digit-sum loopsO((log n)²) digit ops for typical inputsO(1)
Digital-root formulaO(1) arithmeticO(1)
Range [1, U]U times the single-check costO(1)

Summary

  • Definition: collapse n by summing decimal digits until one digit remains; magic iff that digit is 1.
  • Code: nested loops (outer until n ≤ 9, inner digit sum) mirror interview explanations cleanly in JavaScript.
  • Optional: digital-root shortcut for O(1) checks once you are comfortable with the loop version.
Did you know?

Repeatedly summing decimal digits until you reach a single digit is the same idea as the digital root in base 10. For this page, a magic number is one whose digital root is 1 (for example 191+9=101+0=1).

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