Check Harshad Number in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Digit sum

What you’ll learn

  • The Harshad (Niven) rule in base 10: n is divisible by s(n), the sum of decimal digits.
  • A safe isHarshad 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 (%), Math.floor, loops, and if.

  • console.log, Number.isSafeInteger.
  • 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 assign n = Math.floor(n / 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 (digitSumPositive, isHarshad), with explicit guards so n % 0 never runs.

JavaScript
function digitSumPositive(n) {
  let sum = 0;
  while (n > 0) {
    sum += n % 10;
    n = Math.floor(n / 10);
  }
  return sum;
}

function isHarshad(number) {
  const original = number;
  if (number <= 0) {
    return false;
  }
  const sum = digitSumPositive(number);
  if (sum === 0) {
    return false;
  }
  return original % sum === 0;
}

const num = 18;

if (isHarshad(num)) {
  console.log(num + " is a Harshad number.");
} else {
  console.log(num + " is not a Harshad number.");
}
Try it Yourself

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.

JavaScript
function digitSumPositive(n) {
  let sum = 0;
  while (n > 0) {
    sum += n % 10;
    n = Math.floor(n / 10);
  }
  return sum;
}

function isHarshad(num) {
  const original = num;
  if (num <= 0) {
    return false;
  }
  const sum = digitSumPositive(num);
  if (sum === 0) {
    return false;
  }
  return original % sum === 0;
}

const LIMIT = 20;
console.log("Harshad numbers in the range 1 to " + LIMIT + ":");
const parts = [];
for (let i = 1; i <= LIMIT; i++) {
  if (isHarshad(i)) {
    parts.push(String(i));
  }
}
console.log(parts.join(" "));
Try it Yourself

Explanation

11, 13, 14, 15, 16, 17, and 19 fail the final modulus test; the rest in the interval 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 NaN in JavaScript. 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 num 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 NaN in JavaScript.

Zero

n = 0

Not a positive Harshad number; reject before the modulus.

Negatives

n < 0

A while (n > 0) digit loop skips digits; normalize with Math.abs only if you define Harshad for negative inputs.

Trailing zeros

Large n

Digit sums stay small relative to n; stay within safe integers for huge inputs.

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