Check Harshad Number in PHP

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digit sum

What you’ll learn

  • The Harshad (Niven) rule in base 10: n divides s(n), the sum of decimal digits.
  • A safe is_harshad implementation that avoids division by zero for invalid inputs.
  • A range scan for 1 ≤ n ≤ 20 matching the reference output, plus a live preview.

Overview

Harshad numbers combine a digit walk with one divisibility test. They appear in recreational number theory and as quick loop exercises on interviews.

Two programs

18 and the 1–20 list from the reference.

Live preview

Positive safe integers; shows digit sum and remainder.

Rigor

n > 0, s(n) > 0 for the modulus, and clear base-10 scope.

Prerequisites

Integer remainder (%), loops, and if.

  • Basic PHP syntax, loops, functions, and echo.
  • Divisibility: a % b == 0 means b divides a (for b != 0).

What is a Harshad number?

A positive integer n is Harshad in base 10 if s(n) | n, where s(n) is the sum of the decimal digits of n.

For 18, digits sum to 9, and 18 = 9 · 2, so 18 is Harshad (the reference example).

18 s = 9
11 s = 2
Test n % s == 0

Formal divisibility

Write s(n) = ∑i di for decimal digits di. Then n is Harshad iff n ≡ 0 (mod s(n)) and s(n) > 0 (automatic for n > 0 in base 10).

20

s(20) = 2 and 20 mod 2 = 0, so 20 appears in the small range list.

Intuition

18 Harshad
Check
18 % 9 == 0
11 Not
Check
11 % 2 != 0

Takeaway: single-digit numbers are always Harshad in base 10 because s(n) = n.

Live preview

Positive integers in the JavaScript safe range.

Try 1, 12, or 11.

Live result
Press “Check Harshad”.

Algorithm

Goal: decide whether n > 0 is divisible by the sum of its decimal digits.

Digit sum

Initialize s = 0. While n > 0, add n % 10 to s and divide n by 10. Keep a copy of the original n before the loop.

Divisibility

If s > 0 and original % s == 0, report Harshad.

📜 Pseudocode

Pseudocode
function digit_sum_base10(n):  // assume n >= 0
    s = 0
    while n > 0:
        s += (n mod 10)
        n = floor(n / 10)
    return s

function is_harshad(n):
    if n <= 0:
        return false
    s = digit_sum_base10(n)
    if s == 0:
        return false
    return (n mod s) = 0
1

Single value: 18

Same behavior as the reference (isHarshadNumber) with a safe zero guard to prevent division by zero.

php
<?php
function isHarshadNumber(int $number): bool
{
    if ($number <= 0) {
        return false;
    }

    $originalNumber = $number;
    $sumOfDigits = 0;

    while ($number > 0) {
        $sumOfDigits += $number % 10;
        $number = intdiv($number, 10);
    }

    if ($sumOfDigits === 0) {
        return false;
    }

    return $originalNumber % $sumOfDigits === 0;
}

$number = 18;

echo isHarshadNumber($number)
    ? "$number is a Harshad number.\n"
    : "$number is not a Harshad number.\n";
?>

Explanation

For 18, the digit sum is 9. Since 18 % 9 == 0, the function returns true.

2

Harshad numbers in [1, 20]

Same listing as the reference: 1 2 3 4 5 6 7 8 9 10 12 18 20.

php
<?php
function isHarshadNumber(int $number): bool
{
    if ($number <= 0) {
        return false;
    }

    $sumOfDigits = 0;
    $n = $number;

    while ($n > 0) {
        $sumOfDigits += $n % 10;
        $n = intdiv($n, 10);
    }

    if ($sumOfDigits === 0) {
        return false;
    }

    return $number % $sumOfDigits === 0;
}

$rangeStart = 1;
$rangeEnd = 20;

echo "Harshad numbers in the range $rangeStart to $rangeEnd:\n";

for ($i = $rangeStart; $i <= $rangeEnd; $i++) {
    if (isHarshadNumber($i)) {
        echo $i . " ";
    }
}

echo "\n";
?>

Explanation

11, 13, 14, 15, 16, 17, and 19 fail the final modulus test; the rest pass.

Extensions

Precompute sums. For scanning huge intervals, digit DP or incremental updates can amortize work; overkill for n ≤ 20.

Other bases. Generalize the digit extractor with radix b to test Harshad-b numbers.

Interview: mention n > 0 and never dividing by a zero digit sum.

❓ FAQ

A positive integer n is a Harshad (or Niven) number in base 10 if n is divisible by the sum of its decimal digits. Example: 18 has digit sum 9 and 18 is divisible by 9.
Yes. The digit sum of 1 is 1, and 1 is divisible by 1.
For n = 0 the usual digit loop yields sum 0, and n % 0 is undefined in PHP. The definition is for positive integers, so reject n <= 0 before dividing.
Yes. Replace decimal digits with base-b digits and use the same divisibility test. Base-10 Harshad numbers are the common interview default.
O(log10 n) digit operations to compute the digit sum, plus O(1) for the final modulus test.
The digit sum appears in digital root ideas, but Harshad only needs one sum, not iterated reduction to a single digit.

🔄 Input / output examples

Change number in Example 1 or the loop bound in Example 2.

ns(n)Harshad?
11Yes
123Yes
112No
189Yes

Edge cases and pitfalls

The reference logic assumes a positive number. Without guards, n == 0 yields s = 0 and % 0, which is undefined behavior in PHP.

Zero

n = 0

Not a positive Harshad number; reject before the modulus.

Negatives

n < 0

A while (n > 0) digit loop skips negatives in this form; this page keeps the standard positive-only definition.

Trailing zeros

Large n

Digit sums stay small relative to n; overflow is rare unless you multiply partial results incorrectly.

Base

Radix

Clarify base 10 in APIs; other bases change both digits and the divisor.

⏱️ Time and space complexity

TaskTimeExtra space
One nO(log n) decimal digitsO(1)
Scan [1, N]O(N log N) digit work totalO(1)

Here log n means base-10 logarithm: proportional to the number of decimal digits of n.

Summary

  • Rule: positive n is Harshad iff n % digit_sum(n) == 0.
  • Code: preserve original, accumulate sum, guard sum != 0.
  • Watch-outs: n ≤ 0, base radix, and never dividing by a zero digit sum.
Did you know?

The same class of integers is often called Niven numbers in English-language sources (after Ivan Niven’s 1977 talk); Harshad comes from Sanskrit and means “joy-giver.”

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