Check Harshad Number in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digit sum

What You’ll Learn

A Harshad (Niven) number is divisible by the sum of its own digits. This tutorial covers the rule, safe guards, a live preview, worked JavaScript examples, edge cases, and complexity.

Definition

n % s(n) == 0

Positive n is Harshad if divisible by its digit sum.

Classic 18

Yes

1 + 8 = 9 and 18 % 9 == 0.

Digit Peel

% 10 / Math.floor

Accumulate digits with modulus and integer division.

Zero Guard

Avoid % 0

Reject nonpositive n; never divide by a zero sum.

Live Preview

Try any n

See digit sum, remainder, and verdict instantly.

O(log n)

Per check

Time tracks the number of decimal digits.

Introduction

A Harshad number (also called a Niven number) is a positive integer that is divisible by the sum of its decimal digits. Example: 18 has digit sum 9, and 18 % 9 == 0.

Interview prompts usually ask for a boolean check or a small range listing. The core work is one digit-sum pass, a nonzero-sum guard, then a single modulus.

Why it matters?

It drills digit peeling and divisibility in a short warm-up — a natural follow-up after happy numbers.

Key Highlights

One Digit Sum

Compute s(n) once, then test n % s(n).

1–9 Always Yes

Every one-digit positive integer is Harshad.

Two Styles

Loop with % and Math.floor, or sum over String digits.

Positive Only

Reject 0 and negatives by definition.

In short: for positive n, sum the digits, guard against zero, and check whether n is divisible by that sum.

📝 Problem & Approach

Given a positive integer n, decide whether n is divisible by the sum of its decimal digits.

JavaScript
// 18 → s=9  → 18 % 9 === 0  → Harshad
// 11 → s=2  → 11 % 2 !== 0  → not Harshad
// 1  → s=1  → always Harshad

Inputs & Outputs

ItemTypeDescription
nnumberPositive integer (reject n ≤ 0).
Return / printbool / texttrue if n is Harshad.

Minimal workflow

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

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

Method comparison

MethodIdeaNotes
Arithmetic loop% 10 and Math.floor(n / 10)Interview default — no string conversion
String digitsString(n).split(...).reduce(...)Very short in JavaScript
Other basesPeel with base bSame rule; digits change with base

⚡ Quick Reference

GoalPattern
Last digitn % 10
Drop digitn //= 10
Digit sumtotal += n % 10
Harshad tests != 0 and n % s == 0
Yes classics1, 12, 18, 20
No classics11, 19

📋 Loop vs String vs Other Bases

Same rule — pick the digit extractor that fits the interview.

Arithmetic
% 10 / Math.floor(n/10)

Classic; no string conversion

String sum
sum(int(d)...)

Short and readable in JavaScript

Other base
peel base b

Same divisibility idea, different digits

Interview tip
guard first

State positive-only + nonzero sum

Context

When This Problem Shows Up

Reach for Harshad checks when digit sums meet divisibility.

  1. Interview warm-ups

    Digit loops plus a clean modulus check.

  2. After happy numbers

    Same digit peeling; simpler stop condition.

  3. Range listing tasks

    Print all Harshad numbers in 1…N for small N.

  4. Teaching divisibility

    Show that digit sum is a meaningful divisor.

  5. Positive-only scope

    State that 0 / negatives are out of scope.

Key benefit: a tiny boolean problem that still forces careful input validation and a zero-sum guard.

🔮 Live Preview

Positive integers only, within JavaScript safe range.

Try 1, 12, 11, or 20.

Live result
Press “Check Harshad”.

Examples Gallery

Three complete JavaScript programs — single check for 18, range 1–20, and a string digit-sum style. Click View Output to reveal sample console results.

📚 Getting Started

Safe digit-sum helper and one divisibility test.

Example 1 — Single Value: 18

Checks one number with positive-input and zero-sum guards.

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

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

const number = 18;
if (isHarshad(number)) {
  console.log(`${number} is a Harshad number.`);
} else {
  console.log(`${number} is not a Harshad number.`);
}

How It Works

For 18, digit sum is 9 and 18 is divisible by 9. The early returns keep nonpositive inputs and a zero sum from reaching the modulus.

⚡ Range Output

Reuse the same helper to filter a beginner interval.

Example 2 — Harshad Numbers in [1, 20]

Checks each number independently and prints only Harshad ones.

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

function isHarshad(num) {
  if (num <= 0) {
    return false;
  }
  const s = digitSumPositive(num);
  return s !== 0 && num % s === 0;
}

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

How It Works

Numbers like 11 and 19 fail because they are not divisible by their digit sums. All one-digit values pass automatically.

⚙️ String Digit Sum

Same rule with a String-based digit extractor.

Example 3 — Sum Digits via String

Compact digit sum using String(n).split("") and reduce.

JavaScript
function digitSumStr(n) {
  return String(n)
    .split("")
    .reduce((sum, d) => sum + Number(d), 0);
}

function isHarshadStr(n) {
  if (n <= 0) {
    return false;
  }
  const s = digitSumStr(n);
  return s !== 0 && n % s === 0;
}

for (const value of [18, 11, 1, 20]) {
  const label = isHarshadStr(value) ? "Harshad" : "not Harshad";
  console.log(`${value}: ${label}`);
}

How It Works

Converting to a string walks each character digit without a manual loop. Prefer the arithmetic version when the interviewer wants language-agnostic digit peeling.

🧠 How the Algorithm Decides

1

Validate input

Reject n ≤ 0 under the standard definition.

Guard
2

Sum digits

Peel with % 10 and Math.floor(n / 10) (or sum string digits).

s(n)
3

Test divisibility

If s > 0 and n % s == 0, it is Harshad.

Verdict
=

Harshad or not

Remainder 0 → yes; otherwise no.

🔎 Worked Walkthrough — n = 18

Trace digit summing and the final modulus for the classic Harshad example.

StepWorking nActiontotal
11818 % 10 → 88
211 % 10 → 19
30loop endss = 9
418 % 90 → Harshad

Remainder 0 → 18 is Harshad.

Use Cases

Where Harshad checks show up beyond the interview prompt.

1. Interview Warm-Ups

Digit peeling plus a single modulus.

Example: write isHarshad(n).

2. Teaching Divisibility

Connect digit sum to modular arithmetic.

Example: 20 mod 2 = 0.

3. Range Filters

List Harshad numbers in a classroom interval.

Example: 1 to 20 list above.

4. Digit Practice

% 10 / Math.floor(n / 10) drills before harder digit problems.

Example: before Disarium.

5. Base Variants

Same idea with digits in base b.

Example: peel with n % b.

6. Validation Habits

Practice rejecting invalid inputs early.

Example: n ≤ 0 → false.

Pro Tip: say “Harshad means divisible by digit sum” and mention the zero-sum guard before coding.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Clear Rule

    One sentence: n divisible by sum of its digits.

  2. 2. Tiny Code

    One helper and one boolean — easy to whiteboard.

  3. 3. Famous Tests

    18 vs 11 makes verification quick.

  4. 4. Easy Extensions

    Range scans, other bases, string digit sums.

Pro Tip: lead with the arithmetic digit loop; offer the string version if asked for idiomatic JavaScript.

Usage Tips

Small habits that keep Harshad solutions interview-ready.

  1. 1. Extract Digit Sum First

    Write a pure helper before the divisibility check.

  2. 2. Guard Positive n

    Reject n ≤ 0 under the standard definition.

  3. 3. Spot-Check 18 and 11

    Yes and no classics catch bugs fast.

  4. 4. Never Mod by Zero

    Check s != 0 before n % s.

  5. 5. Name the Base

    Say “base 10” so other-base follow-ups are clear.

Pro Tip: all digits 1–9 are Harshad — say that when asked about the smallest cases.

Common Pitfalls

Mistakes that commonly break Harshad solutions.

  1. 1. Modulus by Zero

    Calling n % s when s is 0 (e.g. n = 0).

    → Guard positive n and nonzero sum.

  2. 2. Accepting Negatives

    Standard definition is positive integers only.

    → Reject n ≤ 0.

  3. 3. Confusing With Digital Root

    Repeated digit reduction is a different problem.

    → Harshad uses one sum, then divisibility.

  4. 4. Squaring Digits by Habit

    Happy-number muscle memory can sneak in.

    → Sum digits plain — no squares.

  5. 5. Mutating the Original n

    Destroying n inside digit_sum before the modulus.

    → Work on a local copy; keep original for n % s.

Edge Cases

Validate positivity first to avoid an invalid modulus.

n = 1

One-digit yes

digit_sum(1)=1 and 1 % 1 == 0.

n = 0

Not positive

Not Harshad under this tutorial definition.

Negative

n < 0

Reject unless you explicitly redefine behavior.

Base

Decimal default

Rule is base-dependent; this page uses base 10.

11

Classic no

s(11)=2 and 11 % 2 != 0.

Range

1 to 20

Expect 1–10, 12, 18, 20 (skip 11, 13–17, 19).

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Definition. Positive n is Harshad in base 10 iff n ≡ 0 (mod s(n)).
  • One-digit. Every integer from 1 to 9 is Harshad.
  • Also Niven. Same concept under another common name.
  • Not digital root. Harshad stops after one sum; digital root repeats until one digit.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Classify classics

  • 1, 12, 18, 20 → Harshad
  • 11, 19 → not

2. Match both styles

  • Loop vs string digit sum
  • Assert identical booleans

3. Range 1 to 100

  • List all Harshad numbers
  • Compare with a known list

4. Print the check

  • Show n, s(n), and n % s(n)
  • Great for debugging interviews

Notes

  • Rule: positive n is Harshad if n % digit_sum(n) == 0.
  • Code: compute sum, guard zero, then test divisibility.
  • Watch-outs: reject n ≤ 0 and keep the base explicit.
  • Per check: O(number of digits) time with O(1) extra space.

Quick Takeaway: sum the digits of positive n; if that sum divides n, the number is Harshad.

⏱️ Time and Space Complexity

TaskTimeExtra space
One valueO(log n) digitsO(1)
String digit sumO(log n)O(log n) for the string
Scan [1, N]O(N log N) digit workO(1)

log n here means the number of decimal digits.

Wrap Up

🎉 Conclusion

Harshad (Niven) numbers are positive integers divisible by their digit sum. Keep the check tiny: validate input, sum digits, guard against zero, then take the modulus.

Practice the three examples above, then continue to Automorphic Number for another classic number-theory warm-up.

Remainder 0 means Harshad; never run the modulus when the digit sum is 0.

💡 Best Practices

✅ Do

  • Write a pure digit-sum helper
  • Guard positive n and nonzero sum
  • Test 18, 11, and 1
  • State base 10 explicitly
  • Prefer % // for interviews

❌ Don’t

  • Modulus by a zero digit sum
  • Accept 0 or negatives silently
  • Square digits (that is happy numbers)
  • Confuse with digital-root reduction
  • Mutate n before the final % check

Key Takeaways

Knowledge Unlocked

Five things to remember about Harshad numbers

Decide Harshad the interview-friendly way.

5
Core concepts
Σ 02

Sum

Digit peel

Digits
0 03

Guard

No % by 0

Safety
18 04

Classic

18 yes / 11 no

Tests
O 05

Cost

O(log n)

Analysis

❓ Frequently Asked Questions

A positive integer n is Harshad in base 10 if n is divisible by the sum of its decimal digits.
Yes. digitSum(1)=1 and 1 % 1 = 0. All one-digit positive numbers are Harshad.
For n=0, digit sum becomes 0 and modulus by 0 is invalid (NaN in JavaScript). Standard definition uses positive n.
Yes, by using digits in that base and the same divisibility rule. This page uses base 10.
O(log10 n) digit operations plus one modulus — linear in the number of digits.
Both use digit sums, but Harshad uses one sum and a divisibility check, not repeated reduction to a single digit.
No. digitSum(11)=2 and 11 % 2 != 0.
Both work. %10 with Math.floor is classic interview style; splitting String(n) is shorter in JavaScript.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

Did you Know? 🔊

Harshad numbers are also called Niven numbers. The word “Harshad” comes from Sanskrit and means “joy-giver.”

Continue to Automorphic Number

Learn how automorphic numbers end with their own square in decimal form.

Automorphic number tutorial →

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