- Check
18 % 9 === 0
Check Harshad Number in JavaScript
What you’ll learn
- The Harshad (Niven) rule in base 10:
nis divisible bys(n), the sum of decimal digits. - A safe
isHarshadimplementation that avoids division by zero for invalid inputs. - A range scan for
1 ≤ n ≤ 20matching 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 === 0meansbdividesa(forb !== 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).
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).
20s(20) = 2 and 20 mod 2 = 0, so 20 appears in the small range list.
Intuition
- 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.
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
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) = 0Single value: 18
Same behavior as the reference (digitSumPositive, isHarshad), with explicit guards so n % 0 never runs.
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.");
}Explanation
For 18, the digit sum is 9. Since 18 % 9 === 0, the function returns true.
Harshad numbers in [1, 20]
Same listing as the reference: 1 2 3 4 5 6 7 8 9 10 12 18 20.
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(" "));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
🔄 Input / output examples
Change num in Example 1 or the loop bound in Example 2.
| n | s(n) | Harshad? |
|---|---|---|
1 | 1 | Yes |
12 | 3 | Yes |
11 | 2 | No |
18 | 9 | Yes |
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.
n = 0
Not a positive Harshad number; reject before the modulus.
n < 0
A while (n > 0) digit loop skips digits; normalize with Math.abs only if you define Harshad for negative inputs.
Large n
Digit sums stay small relative to n; stay within safe integers for huge inputs.
Radix
Clarify base 10 in APIs; other bases change both digits and the divisor.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
One n | O(log n) decimal digits | O(1) |
Scan [1, N] | O(N log N) digit work total | O(1) |
Here log n means base-10 logarithm: proportional to the number of decimal digits of n.
Summary
- Rule: positive
nis Harshad iffn % digit_sum(n) === 0. - Code: preserve
original, accumulatesum, guardsum !== 0. - Watch-outs:
n ≤ 0, base radix, and never dividing by a zero digit sum.
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.”
8 people found this page helpful
