Definition
n % s(n) == 0
Positive n is Harshad if divisible by its digit sum.
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.
n % s(n) == 0
Positive n is Harshad if divisible by its digit sum.
Yes
1 + 8 = 9 and 18 % 9 == 0.
% 10 / Math.floor
Accumulate digits with modulus and integer division.
Avoid % 0
Reject nonpositive n; never divide by a zero sum.
Try any n
See digit sum, remainder, and verdict instantly.
Per check
Time tracks the number of decimal digits.
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.
It drills digit peeling and divisibility in a short warm-up — a natural follow-up after happy numbers.
Compute s(n) once, then test n % s(n).
Every one-digit positive integer is Harshad.
Loop with % and Math.floor, or sum over String digits.
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.
Given a positive integer n, decide whether n is divisible by the sum of its decimal digits.
// 18 → s=9 → 18 % 9 === 0 → Harshad
// 11 → s=2 → 11 % 2 !== 0 → not Harshad
// 1 → s=1 → always Harshad | Item | Type | Description |
|---|---|---|
n | number | Positive integer (reject n ≤ 0). |
| Return / print | bool / text | true if n is Harshad. |
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 | Idea | Notes |
|---|---|---|
| Arithmetic loop | % 10 and Math.floor(n / 10) | Interview default — no string conversion |
| String digits | String(n).split(...).reduce(...) | Very short in JavaScript |
| Other bases | Peel with base b | Same rule; digits change with base |
| Goal | Pattern |
|---|---|
| Last digit | n % 10 |
| Drop digit | n //= 10 |
| Digit sum | total += n % 10 |
| Harshad test | s != 0 and n % s == 0 |
| Yes classics | 1, 12, 18, 20 |
| No classics | 11, 19 |
Same rule — pick the digit extractor that fits the interview.
% 10 / Math.floor(n/10)Classic; no string conversion
sum(int(d)...)Short and readable in JavaScript
peel base bSame divisibility idea, different digits
guard firstState positive-only + nonzero sum
Reach for Harshad checks when digit sums meet divisibility.
Digit loops plus a clean modulus check.
Same digit peeling; simpler stop condition.
Print all Harshad numbers in 1…N for small N.
Show that digit sum is a meaningful divisor.
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.
Positive integers only, within JavaScript safe range.
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.
Safe digit-sum helper and one divisibility test.
18Checks one number with positive-input and zero-sum guards.
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.`);
} 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.
Reuse the same helper to filter a beginner interval.
Checks each number independently and prints only Harshad ones.
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(" ")); Numbers like 11 and 19 fail because they are not divisible by their digit sums. All one-digit values pass automatically.
Same rule with a String-based digit extractor.
StringCompact digit sum using String(n).split("") and reduce.
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}`);
} Converting to a string walks each character digit without a manual loop. Prefer the arithmetic version when the interviewer wants language-agnostic digit peeling.
Reject n ≤ 0 under the standard definition.
Peel with % 10 and Math.floor(n / 10) (or sum string digits).
If s > 0 and n % s == 0, it is Harshad.
Remainder 0 → yes; otherwise no.
n = 18Trace digit summing and the final modulus for the classic Harshad example.
| Step | Working n | Action | total |
|---|---|---|---|
| 1 | 18 | 18 % 10 → 8 | 8 |
| 2 | 1 | 1 % 10 → 1 | 9 |
| 3 | 0 | loop ends | s = 9 |
| 4 | — | 18 % 9 | 0 → Harshad |
Remainder 0 → 18 is Harshad.
Where Harshad checks show up beyond the interview prompt.
Digit peeling plus a single modulus.
Example: write isHarshad(n).
Connect digit sum to modular arithmetic.
Example: 20 mod 2 = 0.
List Harshad numbers in a classroom interval.
Example: 1 to 20 list above.
% 10 / Math.floor(n / 10) drills before harder digit problems.
Example: before Disarium.
Same idea with digits in base b.
Example: peel with n % b.
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.
Why this pattern works well in interviews and classwork.
One sentence: n divisible by sum of its digits.
One helper and one boolean — easy to whiteboard.
18 vs 11 makes verification quick.
Range scans, other bases, string digit sums.
Pro Tip: lead with the arithmetic digit loop; offer the string version if asked for idiomatic JavaScript.
Small habits that keep Harshad solutions interview-ready.
Write a pure helper before the divisibility check.
Reject n ≤ 0 under the standard definition.
Yes and no classics catch bugs fast.
Check s != 0 before n % s.
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.
Mistakes that commonly break Harshad solutions.
Calling n % s when s is 0 (e.g. n = 0).
→ Guard positive n and nonzero sum.
Standard definition is positive integers only.
→ Reject n ≤ 0.
Repeated digit reduction is a different problem.
→ Harshad uses one sum, then divisibility.
Happy-number muscle memory can sneak in.
→ Sum digits plain — no squares.
Destroying n inside digit_sum before the modulus.
→ Work on a local copy; keep original for n % s.
Validate positivity first to avoid an invalid modulus.
digit_sum(1)=1 and 1 % 1 == 0.
Not Harshad under this tutorial definition.
n < 0Reject unless you explicitly redefine behavior.
Rule is base-dependent; this page uses base 10.
s(11)=2 and 11 % 2 != 0.
Expect 1–10, 12, 18, 20 (skip 11, 13–17, 19).
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
n % digit_sum(n) == 0.Quick Takeaway: sum the digits of positive n; if that sum divides n, the number is Harshad.
| Task | Time | Extra space |
|---|---|---|
| One value | O(log n) digits | O(1) |
| String digit sum | O(log n) | O(log n) for the string |
Scan [1, N] | O(N log N) digit work | O(1) |
log n here means the number of decimal digits.
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.
Decide Harshad the interview-friendly way.
n % s(n) == 0
DefinitionDigit peel
DigitsNo % by 0
Safety18 yes / 11 no
TestsO(log n)
AnalysisHarshad numbers are also called Niven numbers. The word “Harshad” comes from Sanskrit and means “joy-giver.”
Learn how automorphic numbers end with their own square in decimal form.
8 people found this page helpful