Check Magic Number in PHP

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code Examples
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 matching classic examples (19, range 1–50).
  • A browser live preview, pseudocode, complexity notes, 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 directly in the browser.

Tables & rigor

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

Prerequisites

Loops, integer division, and the remainder operator in PHP.

  • Basic PHP function syntax and echo output.
  • Extracting digits with n % 10 and 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 digit-sum chain. 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.)

Reduce

While n > 9, replace n by the sum of its decimal digits using % 10 and / 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. Outer loop continues until one digit remains; inner loop computes the digit sum.

c
<?php
function isMagicNumber(int $num): bool
{
    if ($num <= 0) {
        return false;
    }

    while ($num > 9) {
        $sum = 0;
        while ($num > 0) {
            $sum += $num % 10;
            $num = intdiv($num, 10);
        }
        $num = $sum;
    }

    return $num === 1;
}

$number = 19;
echo isMagicNumber($number)
    ? "$number is a Magic Number.\n"
    : "$number is not a Magic Number.\n";
?>

Explanation

The outer while ($num > 9) keeps collapsing the value; the inner while performs one digit-sum pass. 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.

c
<?php
function isMagicNumber(int $num): bool
{
    if ($num <= 0) {
        return false;
    }

    while ($num > 9) {
        $sum = 0;
        while ($num > 0) {
            $sum += $num % 10;
            $num = intdiv($num, 10);
        }
        $num = $sum;
    }

    return $num === 1;
}

echo "Magic Numbers in the range 1 to 50:\n";
for ($i = 1; $i <= 50; $i++) {
    if (isMagicNumber($i)) {
        echo $i . " ";
    }
}
echo "\n";
?>

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. Many teams still prefer the explicit loop in interviews because it is easier to trace on the whiteboard.

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)^2) for practical fixed-width integer inputs.

🔄 Input / output examples

For the single-number program, typical lines look like this (you can swap in scanf 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, 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 intO(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.
  • 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