2018-09-30 22:01:58 +00:00
---
id: 595668ca4cfe1af2fb9818d4
2020-11-27 18:02:05 +00:00
title: Harshad or Niven series
2018-09-30 22:01:58 +00:00
challengeType: 5
2019-08-05 16:17:33 +00:00
forumTopicId: 302281
2021-01-13 02:31:00 +00:00
dashedName: harshad-or-niven-series
2018-09-30 22:01:58 +00:00
---
2020-11-27 18:02:05 +00:00
# --description--
2019-05-23 04:57:59 +00:00
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
2020-11-27 18:02:05 +00:00
For example, `42` is a [Harshad number ](https://rosettacode.org/wiki/Harshad_or_Niven_series "Harshad or Niven series" ) as `42` is divisible by `(4 + 2)` without remainder.
2018-09-30 22:01:58 +00:00
Assume that the series is defined as the numbers in increasing order.
2020-11-27 18:02:05 +00:00
# --instructions--
2019-03-05 09:37:06 +00:00
Implement a function to generate successive members of the Harshad sequence.
2020-11-27 18:02:05 +00:00
2019-03-05 09:37:06 +00:00
Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --hints--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`isHarshadOrNiven` should be a function.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert(typeof isHarshadOrNiven === 'function');
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
`isHarshadOrNiven()` should return `{"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 22:01:58 +00:00
```js
2020-11-27 18:02:05 +00:00
assert.deepEqual(isHarshadOrNiven(), res);
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
# --seed--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
## --after-user-code--
2018-09-30 22:01:58 +00:00
```js
2018-10-20 18:02:47 +00: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 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
## --seed-contents--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
function isHarshadOrNiven() {
const res = {
firstTwenty: [],
firstOver1000: undefined
};
// Only change code below this line
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
return res;
}
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --solutions--
2018-09-30 22:01:58 +00:00
```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;
}
```