Harshad numbers in JavaScript
Intermediate · 4 min read
A Harshad number is a number that divides evenly by the sum of its own digits. 18 is one: its digits add up to 1 + 8 = 9, and 18 divided by 9 is 2, with nothing left over. 19 is not: its digits add up to 10, and 19 doesn't divide by 10.
The name comes from Sanskrit and means "great joy". These numbers are a favorite in coding interviews and puzzle sites because they combine two small skills: summing digits and testing divisibility. In this tutorial you will write isHarshad(n), list the Harshad numbers up to 30, count them up to 100, and then reason about why no prime above 9 can ever be one. You need to know loops and the % operator.
The two pieces you need
The digit sum adds up a number's digits. You get each digit with n % 10 (the last digit) and remove it with Math.floor(n / 10), repeating until nothing is left.
Divisibility is a remainder check: a % b === 0 means b divides a evenly.
console.log(18 % 9); // 0: 9 divides 18
console.log(19 % 10); // 9: 10 doesn't divide 19
Put them together and you have the whole test.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
46 Harshad numbers
fairA Harshad number is divisible by the sum of its own digits. List them up to 30, count how many there are up to 100, and show that no prime above 9 can be one.
Stuck? Three hints, smallest first
- 1. Reuse the digit sum from exercise 42, then test
n % digitSum(n) === 0. - 2. Every single-digit number qualifies, since
n % nis 0. - 3. For a prime
pto be Harshad, its digit sum would have to be 1 orpitself.
Step 1: the digit sum
function digitSum(n) {
let rest = Math.abs(n);
let sum = 0;
while (rest > 0) {
sum += rest % 10;
rest = Math.floor(rest / 10);
}
return sum;
}
console.log(digitSum(18)); // 9
console.log(digitSum(1729)); // 19
rest is a copy we can wear down digit by digit, so the original n stays as it was.
Step 2: the Harshad test
A first try is one line:
const isHarshadFirstTry = (n) => n % digitSum(n) === 0;
console.log(isHarshadFirstTry(18)); // true
console.log(isHarshadFirstTry(19)); // false
console.log(isHarshadFirstTry(-18)); // true
It works for 18 and 19, but it also says -18 is a Harshad number. -18 % 9 is -0, and -0 === 0 is true in JavaScript. Harshad numbers are defined for positive whole numbers only, so add a guard:
const isHarshad = (n) => n > 0 && n % digitSum(n) === 0;
console.log(isHarshad(-18)); // false
console.log(isHarshad(0)); // false
&& stops at the first false, so for 0 or a negative number the digit sum is never even computed.
Step 3: list them up to 30
const upTo30 = [];
for (let n = 1; n <= 30; n++) if (isHarshad(n)) upTo30.push(n);
console.log(upTo30.join(', ')); // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30
Two patterns jump out. Every single digit is there, because any number divides itself: 7 % 7 is 0. And 10 is there because its digit sum is 1, and everything divides by 1. The same is true of 100, 1000 and every other power of ten.
Step 4: count up to 100, and find the first miss after it
const upTo100 = [];
for (let n = 1; n <= 100; n++) if (isHarshad(n)) upTo100.push(n);
console.log(upTo100.length); // 33
let firstMiss = 0;
for (let n = 101; !firstMiss; n++) if (!isHarshad(n)) firstMiss = n;
console.log(firstMiss); // 101
A third of the first hundred numbers are Harshad numbers. The second loop has an unusual condition: !firstMiss stays true while firstMiss is 0, so the loop runs until it finds a number that fails. 101 has a digit sum of 2, and it is odd, so it fails right away. 100, before it, passes.
Runs of several in a row exist too:
console.log([110, 111, 112].every(isHarshad)); // true
Step 5: a famous example
console.log(digitSum(1729), 1729 / 19); // 19 91
console.log(isHarshad(1729)); // true
1729 is famous as the "taxicab number", and it is also a Harshad number: its digits sum to 19, and 19 times 91 is 1729.
Step 6: why no prime above 9 works
A prime is only divisible by 1 and itself. So for a prime p to be a Harshad number, its digit sum would have to be either 1 or p.
- A digit sum of 1 means the number is 10, 100, 1000 and so on. None of those is prime.
- A digit sum equal to p is impossible once p has two digits, because a number's digits always add up to less than the number itself. 97 has a digit sum of 16, nowhere near 97.
So no prime above 9 can be a Harshad number. You can confirm it on the primes below 100:
const primes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
console.log(primes.some(isHarshad)); // false
The check only covers these 21 primes. The reasoning is what tells you it holds for every prime.
The full solution
The answer panel has digitSum and isHarshad, builds both lists, finds the first miss above 100 and prints the 18, 19 and 1729 cases. Press Run to see the output.
function digitSum(n) {
let rest = Math.abs(n);
let sum = 0;
while (rest > 0) {
sum += rest % 10;
rest = Math.floor(rest / 10);
}
return sum;
}
const isHarshad = (n) => n > 0 && n % digitSum(n) === 0;
const upTo30 = [];
for (let n = 1; n <= 30; n++) if (isHarshad(n)) upTo30.push(n);
const upTo100 = [];
for (let n = 1; n <= 100; n++) if (isHarshad(n)) upTo100.push(n);
const primes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
let firstMiss = 0;
for (let n = 101; !firstMiss; n++) if (!isHarshad(n)) firstMiss = n;
console.log('Harshad up to 30 :', upTo30);
console.log('how many to 100 :', upTo100.length);
console.log('18 and 19 :', [18, 19].map((n) => [n, digitSum(n), isHarshad(n)]));
console.log('1729 :', digitSum(1729), 1729 / 19);
console.log('first miss > 100 :', firstMiss);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the Harshad numbers up to 30', upTo30, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30]);
test('18 qualifies because 9 divides it; 19 does not, since 10 does not', [isHarshad(18), isHarshad(19)], [true, false]);
test('every single-digit number qualifies trivially', [1, 2, 3, 4, 5, 6, 7, 8, 9].every(isHarshad), true);
test('so does every power of ten, whose digit sum is 1', [10, 100, 1000, 10000].every(isHarshad), true);
test('33 of the first hundred numbers are Harshad', upTo100.length, 33);
test('1729 is one: its digits sum to 19, and 19 x 91 is 1729', [digitSum(1729), isHarshad(1729), 19 * 91], [19, true, 1729]);
test('and 101 is the first failure above 100', firstMiss, 101);
test('110, 111 and 112 are three in a row', [110, 111, 112].every(isHarshad), true);
test('and no prime above 9 can ever be Harshad', primes.some(isHarshad), false);
The prime result is the one worth reasoning through rather than testing. If p is prime, the only numbers dividing it are 1 and p, so a Harshad prime would need a digit sum of 1 — which only powers of ten have — or a digit sum equal to p itself, which is impossible once p has two digits, because the digits of a number always sum to less than the number. The assertion above confirms the argument on the primes below 100; the argument is what tells you it holds for all of them.
Harshad numbers are dense at the bottom: 33 of the first hundred, including every one of the first ten. That density falls away slowly, and runs of consecutive Harshad numbers keep appearing — 110, 111, 112 is one. There is no run of more than 20 in a row anywhere, but that is a much harder result than anything here.
Common mistakes
- Forgetting the
n > 0guard. Without it, negative numbers like -18 pass, because-0 === 0istrue. - Summing digits of the wrong copy. If you wear down
nitself insidedigitSum, you lose the value you need for the division. Work on a copy, likerest. - Trusting a test over the reasoning. Checking primes below 100 doesn't prove anything about primes above it. The digit-sum argument does.
Try it yourself
- Find the first run of four Harshad numbers in a row above 100. (Hint: it starts a little above 500.)
- Write
harshadQuotient(n)that returnsn / digitSum(n)for a Harshad number andnullotherwise. - Count the Harshad numbers up to 1000.