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 C
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
Trace
Worked Walkthrough — n = 19
Sum digits, replace n, and repeat until one digit is left.
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.
C
#include <stdio.h>
#include <stdbool.h>
bool is_magic(int n)
{
if (n <= 0)
{
return false;
}
while (n > 9)
{
int sum = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
}
n = sum;
}
return n == 1;
}
int main(void)
{
int number = 19;
if (is_magic(number))
{
printf("%d is a magic number\\n", number);
}
else
{
printf("%d is not a magic number\\n", number);
}
return 0;
}
Output
19 is a magic number
How It Works
Reject non-positive inputs for the usual interview definition.
Outer while (n > 9) means “keep going until one digit remains.”
Inner loop peels digits with n % 10 and builds sum.
Assign n = sum and repeat. For 19: 10, then 1.
Return whether the final digit equals 1.
Example 2 — Modulo 9 Shortcut
Digital root is 1 exactly when n % 9 == 1 for positive n.