Check Magic Number in Java
Problem
A magic number is one whose digits, when repeatedly summed down to a single digit, eventually reduce to exactly 1.
Given a number, determine whether it is a magic number.
Java Program
public class MagicNumberCheck {
public static void main(String[] args) {
int n = 40213;
int x = n;
while (x >= 10) {
int sum = 0;
while (x > 0) {
sum += x % 10; // peel off the last digit
x /= 10;
}
x = sum; // collapse to the digit sum, then check again
}
System.out.println(n + " is a magic number: " + (x == 1));
}
}Output
Core Logic
Repeatedly collapsing the number down to the sum of its digits, until only one digit is left, mirrors the definition directly — check whether that final digit is 1.
- 1The outer
while (x >= 10)loop keeps collapsingxas long as it still has more than one digit. - 2Inside it, an inner loop peels off digits one at a time with
x % 10andx /= 10, adding each intosum. - 3Once every digit of the current
xhas been consumed,xis replaced by that digit sum. - 4The outer loop repeats this collapse until
xitself is a single digit, and the final check isx == 1.
40213, the digits sum to 4+0+2+1+3=10, and 10 then collapses to 1+0=1 — a single digit of 1, so it's reported as magic.Key Point: This single-digit result is called the digital root — a number's digital root is always between 1 and 9 (never 0, for a positive number), no matter how large it starts out.
Why: Each pass sums the digits of the current value, and the value shrinks fast enough that only a couple of passes are ever needed regardless of how large n starts.
Key Concepts
Approach 2: Digital Root Shortcut
public class MagicNumberShortcut {
public static void main(String[] args) {
int n = 40213;
// The digital root of n is 1 + (n - 1) % 9, so magic numbers are exactly n % 9 == 1
boolean isMagic = n % 9 == 1;
System.out.println(n + " is a magic number: " + isMagic);
}
}
Output
Core Logic
A number's digital root already has a closed-form formula — 1 + (n - 1) mod 9 — so the whole repeated-summing loop can collapse into a single modulo check.
- 1The digital root formula simplifies to exactly this: a number is magic precisely when
n % 9 == 1. - 2
n % 9checks the remainder ofndivided by 9 directly, without ever touching individual digits. - 3If that remainder is
1, the number's digital root must be1, and it's magic.
40213 % 9 evaluates to 1, matching the digital root of 1 found by manually summing digits.Key Point: This works because summing a number's digits never changes its remainder mod 9 — the repeated-digit-sum loop and this one-line check are mathematically the same operation, just expressed differently.
Why: The modulo trick replaces repeated digit summation with a single arithmetic operation, since the digital root of any number follows a fixed formula based on n mod 9.