A magic number is a positive integer whose digits, when repeatedly summed, reduce to a single digit of 1 (digital root = 1).
Remember
while n has more than one digit:
n = sum of digits of n
magic ⇔ final digit == 1
Example: 19
1 + 9 = 10
1 + 0 = 1 ← magic
Example: 18
1 + 8 = 9 ← not magic
n
Reduction
Magic?
1
(already 1)
Yes
10
10 → 1
Yes
19
19 → 10 → 1
Yes
18
18 → 9
No
Approach
How to Check a Magic Number in JavaScript
Four clear steps — then pick a digit-sum loop or the O(1) formula.
Use a positive integer (interview convention).
While the value is greater than 9, replace it with the sum of its digits.
Stop when one digit remains.
Return true if that digit is 1 — or skip loops and test n % 9 === 1.
Method
Idea
Time
Best for
Digit-sum loop
Sum digits until n <= 9, check === 1
O(log n)
Interviews, showing the process
Modulo 9
n % 9 === 1 for n > 0
O(1)
Quick answers, production
Pseudocode
Pseudocode
function IsMagic(n):
if n <= 0:
return false
while n > 9:
sum = 0
while n > 0:
sum = sum + (n mod 10)
n = n / 10
n = sum
return n == 1
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Goal
Digital root equals 1
Stop when
n <= 9
Fast check
n % 9 === 1 (n > 0)
Not happy
Happy uses sum of squares
Same family
Condense / digital root
Classic check
19 yes; 18 no
Try it
Live Preview
Enter a positive integer to see the reduction chain and whether it is magic.
Positive whole numbers. Tap a chip or type a value.
Result
n = 19
Chain: 19 → 10 → 1
Final digit = 1
Verdict: MAGIC NUMBER
Code
JavaScript Programs
Start with the iterative digit-sum loop so you can show each reduction. Then use the O(1) modulo shortcut when speed matters.
Example 1 — Digit-Sum Loop
Keep replacing the number with the sum of its digits until one digit remains, then check for 1.
JavaScript
function isMagic(n) {
if (n <= 0) {
return false;
}
while (n > 9) {
let sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
n = sum;
}
return n === 1;
}
const number = 19;
if (isMagic(number)) {
console.log(number + " is a magic number");
} else {
console.log(number + " is not a magic number");
}