- Steps
- 19 → 10 → 1
Check Magic Number in JavaScript
What you’ll learn
- The usual interview definition: repeated decimal digit sum until one digit remains; magic means that digit is 1.
- A compact
isMagicNumberfunction andconsole.logdrivers 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.isSafeIntegerfor validation in the live widget.- Extracting digits with
n % 10andMath.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.
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.
18 → 1+8 = 9, stops at 9, so it is not magic under this definition. 28 → 10 → 1, so it is magic.
Intuition and examples
- Steps
- 28 → 10 → 1
- 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.
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
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)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.
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.");
}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.
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.
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(" ") + " ");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
🔄 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 number | Typical line printed |
|---|---|
| 19 | 19 is a Magic Number. |
| 18 | 18 is not a Magic Number. |
| 1 | 1 is a Magic Number. |
| 28 | 28 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.
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.
Negative values
Digit extraction on negatives needs a clear rule (often: reject, or use absolute value). The samples here stay strictly positive.
Other “magic” meanings
Compilers also use “magic number” for unexplained literals in code—unrelated to this math exercise.
⏱️ Time and space complexity
| Approach | Time (single n) | Extra space |
|---|---|---|
| Repeated digit-sum loops | O((log n)²) digit ops for typical inputs | O(1) |
| Digital-root formula | O(1) arithmetic | O(1) |
Range [1, U] | U times the single-check cost | O(1) |
Summary
- Definition: collapse
nby summing decimal digits until one digit remains; magic iff that digit is1. - 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.
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 19 → 1+9=10 → 1+0=1).
8 people found this page helpful
