Skip to content

Commit afe39c0

Browse files
feat: add Harshad number algorithm
1 parent 5c39e87 commit afe39c0

2 files changed

Lines changed: 74 additions & 0 deletions

File tree

‎Maths/HarshadNumber.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @function isHarshadNumber
3+
* @description A Harshad number (also called Niven number) is an integer
4+
* that is divisible by the sum of its digits.
5+
* For example, 18 is a Harshad number because 1+8=9 and 18/9=2.
6+
* @param {number} n - A positive integer
7+
* @returns {boolean} - True if n is a Harshad number, false otherwise
8+
* @see https://en.wikipedia.org/wiki/Harshad_number
9+
* @example isHarshadNumber(18) => true
10+
* @example isHarshadNumber(21) => true
11+
* @example isHarshadNumber(19) => false
12+
*/
13+
const isHarshadNumber = (n) => {
14+
if (!Number.isInteger(n) || n < 1) {
15+
throw new TypeError('Input must be a positive integer')
16+
}
17+
const digitSum = String(n)
18+
.split('')
19+
.reduce((sum, d) => sum + Number(d), 0)
20+
return n % digitSum === 0
21+
}
22+
23+
export { isHarshadNumber }

‎Maths/test/HarshadNumber.test.js‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { isHarshadNumber } from '../HarshadNumber.js'
2+
3+
describe('isHarshadNumber', () => {
4+
test('1 is a Harshad number', () => {
5+
expect(isHarshadNumber(1)).toBe(true)
6+
})
7+
8+
test('18 is a Harshad number (1+8=9, 18/9=2)', () => {
9+
expect(isHarshadNumber(18)).toBe(true)
10+
})
11+
12+
test('21 is a Harshad number (2+1=3, 21/3=7)', () => {
13+
expect(isHarshadNumber(21)).toBe(true)
14+
})
15+
16+
test('12 is a Harshad number (1+2=3, 12/3=4)', () => {
17+
expect(isHarshadNumber(12)).toBe(true)
18+
})
19+
20+
test('100 is a Harshad number (1+0+0=1, 100/1=100)', () => {
21+
expect(isHarshadNumber(100)).toBe(true)
22+
})
23+
24+
test('111 is a Harshad number (1+1+1=3, 111/3=37)', () => {
25+
expect(isHarshadNumber(111)).toBe(true)
26+
})
27+
28+
test('19 is NOT a Harshad number (1+9=10, 19/10 is not integer)', () => {
29+
expect(isHarshadNumber(19)).toBe(false)
30+
})
31+
32+
test('11 is NOT a Harshad number', () => {
33+
expect(isHarshadNumber(11)).toBe(false)
34+
})
35+
36+
test('23 is NOT a Harshad number', () => {
37+
expect(isHarshadNumber(23)).toBe(false)
38+
})
39+
40+
test('throws TypeError for zero', () => {
41+
expect(() => isHarshadNumber(0)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for negative input', () => {
45+
expect(() => isHarshadNumber(-18)).toThrow(TypeError)
46+
})
47+
48+
test('throws TypeError for float input', () => {
49+
expect(() => isHarshadNumber(18.5)).toThrow(TypeError)
50+
})
51+
})

0 commit comments

Comments
 (0)