PHP Unhappy Number Program

Beginner
7 min read
Updated: Nov 2026
2 programs
Live preview

What Is an Unhappy Number?

Replace a positive integer with the sum of the squares of its digits, and repeat. If the chain never reaches 1, the number is an unhappy number. It gets stuck in a loop that always passes through 4.

Remember
n is unhappy  ⇔  digit-square chain never reaches 1

Example: 2
  2² = 4
  4² = 16
  1² + 6² = 37
  3² + 7² = 58
  5² + 8² = 89
  8² + 9² = 145
  1² + 4² + 5² = 42
  4² + 2² = 20
  2² + 0² = 4   ← back to 4, cycle

Every unhappy number enters:
  4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
nChain (short)Result
22 → 4 → 16 → … (cycle)Unhappy
44 → 16 → 37 → … → 4Unhappy
1already 1Happy (not unhappy)
77 → 49 → 97 → 130 → 10 → 1Happy (not unhappy)
1919 → 82 → 68 → 100 → 1Happy (not unhappy)

How to Check an Unhappy Number in PHP

Four clear steps — then stop at 4 or use a visited array.

  1. Require n > 0 (positive integers only).
  2. Define f(n) = sum of squares of the digits of n.
  3. Keep applying f until the value is 1 (happy) or you detect a loop (unhappy).
  4. Return true for unhappy: the chain hit 4, or it repeated a value without reaching 1.
MethodIdeaExtra spaceBest for
Stop at 4Loop until n is 1 or 4O(1)Short code, interviews
Visited arrayStop when a value repeatsO(k)No need to know the cycle

Pseudocode

Pseudocode
function SumOfSquares(n):
    total = 0
    while n > 0:
        d = n mod 10
        total = total + d * d
        n = n / 10
    return total

function IsUnhappy(n):
    if n <= 0:
        return false

    while n != 1 and n != 4:
        n = SumOfSquares(n)

    return n == 4

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Core step$total += ($n % 10) ** 2; $n = intdiv($n, 10);
Unhappy whenChain never reaches 1 (it hits 4 or repeats)
Happy whenChain reaches 1
Known cycle4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
Shortcutwhile ($n !== 1 && $n !== 4) { $n = f($n); }
Classic unhappy2, 3, 4, 5, 6, 8, 9, 11
Classic happy1, 7, 10, 13, 19, 23

Live Preview

Enter a positive integer to see the digit-square chain and the unhappy/happy verdict.

Positive whole numbers only. Tap a chip or type a value.

Result
n = 2
Chain: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
Verdict: UNHAPPY NUMBER

Worked Walkthrough — n = 2

Square each digit, add them up, and watch the chain loop back to 4 instead of reaching 1.

Calculation
Step 1: 2² = 4
Step 2: 4² = 16
Step 3: 1² + 6² = 1 + 36 = 37
Step 4: 3² + 7² = 9 + 49 = 58
Step 5: 5² + 8² = 25 + 64 = 89
Step 6: 8² + 9² = 64 + 81 = 145
Step 7: 1² + 4² + 5² = 1 + 16 + 25 = 42
Step 8: 4² + 2² = 16 + 4 = 20
Step 9: 2² + 0² = 4   ← 4 again, so a cycle

Never reached 1 → 2 is unhappy

PHP Programs

Start with the short stop-at-4 check. Then use a visited array when you do not want to rely on the known cycle.

Example 1 — Stop at 4

Every unhappy number reaches 4, so stop there and return true.

php
<?php
function sumOfSquares($n) {
    $total = 0;
    while ($n > 0) {
        $d = $n % 10;
        $total += $d * $d;
        $n = intdiv($n, 10);
    }
    return $total;
}

function isUnhappy($n) {
    if ($n <= 0) {
        return false;
    }

    while ($n !== 1 && $n !== 4) {
        $n = sumOfSquares($n);
    }
    return $n === 4;
}

$number = 2;
if (isUnhappy($number)) {
    echo $number . " is an Unhappy Number.\n";
} else {
    echo $number . " is not an Unhappy Number.\n";
}
?>

How It Works

  1. sumOfSquares() peels digits with % 10 and adds each square.
  2. Reject n <= 0 so only positive integers are checked.
  3. Keep replacing n until it becomes 1 (happy) or 4 (inside the unhappy cycle).
  4. For 2, the chain is 2 → 4, so the loop stops at 4.
  5. return $n === 4; gives true for unhappy numbers and false for happy ones.

Example 2 — Visited Array

Store every value you produce as an array key. Reach 1 → happy; see a repeat first → unhappy.

php
<?php
function sumOfSquares($n) {
    $total = 0;
    while ($n > 0) {
        $d = $n % 10;
        $total += $d * $d;
        $n = intdiv($n, 10);
    }
    return $total;
}

function isUnhappy($n) {
    if ($n <= 0) {
        return false;
    }

    $seen = [];
    while ($n !== 1 && !isset($seen[$n])) {
        $seen[$n] = true;
        $n = sumOfSquares($n);
    }
    return $n !== 1;
}

echo isUnhappy(2) ? "2 is unhappy\n" : "2 is happy\n";
echo isUnhappy(4) ? "4 is unhappy\n" : "4 is happy\n";
echo isUnhappy(7) ? "7 is unhappy\n" : "7 is happy\n";
echo isUnhappy(19) ? "19 is unhappy\n" : "19 is happy\n";
?>

How It Works

  1. Reuse the same sumOfSquares() helper as Example 1.
  2. Add each value to $seen before computing the next one.
  3. If $n becomes 1, the loop ends and $n !== 1 is false — happy.
  4. If $n is already in $seen, the chain is looping without reaching 1, so $n !== 1 is true — unhappy.
  5. This works even if you forget the 4-cycle, at the cost of a little extra memory.

Edge Cases & Pitfalls

Check these before calling the solution done.

1

Not unhappy

1 is happy, so isUnhappy(1) must be false.

Cycle

Must stop

Without a stop at 4 or a visited array, unhappy inputs loop forever.

0 / negatives

Out of scope

The definition is for positive integers. Reject the rest.

Squares

Not digit sum

You square each digit. Plain digit sum is a different problem.

Time and Space Complexity

ProgramTimeExtra space
Stop at 4O(k · log n)O(1)
Visited arrayO(k · log n)O(k)

Each square-sum step costs O(digits). Values shrink quickly into a small range, so k (steps until 1 or a repeat) stays small in practice.

Key Takeaways

  • Definition: keep summing digit squares; if you never reach 1, the number is unhappy.
  • Stop safely: stop at 4 or use a visited array so unhappy inputs do not loop forever.
  • Return value: isUnhappy() is true when the chain hits 4.
  • Test set: 2 and 4 unhappy; 1, 7, and 19 happy.

One line: sum digit squares until you hit 1 (happy) or 4 (unhappy).

Frequently Asked Questions

A positive integer that never reaches 1 when you repeatedly replace it with the sum of the squares of its digits. It ends up looping in the cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.
A number that does reach 1 under the same digit-square process. Every positive integer is either happy or unhappy.
Every unhappy number eventually lands in the cycle that contains 4. So if the process hits 4, you can stop and answer unhappy without storing visited values.
Yes. 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, and it never reaches 1.
No. 1 is already happy because it equals 1. Unhappy numbers never reach 1.
The definition uses positive integers. Reject n <= 0 before running the process.

Next: Whole Number

Check nonnegative whole numbers — natural numbers plus zero.

Whole number tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

11 people found this page helpful