2018-09-30 23:01:58 +01:00
---
title: Harshad or Niven series
id: 595668ca4cfe1af2fb9818d4
challengeType: 5
2019-08-05 09:17:33 -07:00
forumTopicId: 302281
2018-09-30 23:01:58 +01:00
---
## Description
< section id = 'description' >
2019-05-23 13:57:59 +09:00
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
2019-06-14 20:04:16 +09:00
For example, < code > 42< / code > is a < a href = "https://rosettacode.org/wiki/Harshad_or_Niven_series" title = "Harshad or Niven series" target = "_blank" > Harshad number< / a > as < code > 42< / code > is divisible by < code > (4 + 2)< / code > without remainder.
2018-09-30 23:01:58 +01:00
Assume that the series is defined as the numbers in increasing order.
< / section >
## Instructions
< section id = 'instructions' >
2019-03-05 18:37:06 +09:00
Implement a function to generate successive members of the Harshad sequence.
Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000.
2018-09-30 23:01:58 +01:00
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
2019-11-20 07:01:31 -08:00
- text: < code > isHarshadOrNiven</ code > should be a function.
2019-07-26 05:24:52 -07:00
testString: assert(typeof isHarshadOrNiven === 'function');
2018-10-04 14:37:37 +01:00
- text: '< code > isHarshadOrNiven()</ code > should return < code > {"firstTwenty": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],"firstOver1000": 1002}</ code > '
2019-07-24 05:09:23 -07:00
testString: assert.deepEqual(isHarshadOrNiven(), res);
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
2019-03-05 18:37:06 +09:00
function isHarshadOrNiven() {
2018-09-30 23:01:58 +01:00
const res = {
firstTwenty: [],
firstOver1000: undefined
};
// Change after this line
return res;
}
```
< / div >
### After Test
< div id = 'js-teardown' >
```js
2018-10-20 21:02:47 +03:00
const res = {
firstTwenty: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42],
firstOver1000: 1002
};
2018-09-30 23:01:58 +01:00
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
function isHarshadOrNiven() {
const res = {
firstTwenty: [],
firstOver1000: undefined
};
function isHarshad(n) {
let s = 0;
const nStr = n.toString();
for (let i = 0; i < nStr.length ; + + i ) {
s += parseInt(nStr.charAt(i), 10);
}
return n % s === 0;
}
let count = 0;
const harshads = [];
for (let n = 1; count < 20 ; + + n ) {
if (isHarshad(n)) {
count++;
harshads.push(n);
}
}
res.firstTwenty = harshads;
let h = 1000;
while (!isHarshad(++h));
res.firstOver1000 = h;
return res;
}
```
< / section >