Skip to content

Commit ded2ec2

Browse files
committed
feat: check if number is a harshad number
1 parent 1d252d7 commit ded2ec2

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

Maths/isHarshad.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Wikipedia: https://en.wikipedia.org/wiki/Harshad_number
3+
* A Harshad number (or Niven number) is a positive integer that is divisible by the sum of its own digits.
4+
*
5+
* The function checks if a number is a Harshad (Niven) number.
6+
* @param {any} n - The number to check
7+
* @returns {boolean} - true if Harshad, false otherwise
8+
* @example isHarshad(2025) // true
9+
*/
10+
export const isHarshad = (n) => {
11+
const num = Number(n)
12+
13+
if (num <= 0 || !Number.isInteger(num)) return false
14+
15+
let sum = 0,
16+
temp = n
17+
18+
while (temp > 0) {
19+
sum += temp % 10
20+
temp = Math.floor(temp / 10)
21+
}
22+
23+
return n % sum === 0
24+
}

Maths/test/isHarshad.test.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { isHarshad } from '../isHarshad.js'
2+
3+
describe('Harshad number tests', () => {
4+
test('Basic Harshad numbers', () => {
5+
expect(isHarshad(18)).toBe(true)
6+
expect(isHarshad(21)).toBe(true)
7+
expect(isHarshad(12)).toBe(true)
8+
expect(isHarshad(6804)).toBe(true)
9+
expect(isHarshad('18')).toBe(true)
10+
expect(isHarshad(2025)).toBe(true)
11+
})
12+
13+
test('Non-Harshad numbers', () => {
14+
expect(isHarshad(19)).toBe(false)
15+
expect(isHarshad(25)).toBe(false)
16+
expect(isHarshad(97)).toBe(false)
17+
})
18+
19+
test('Edge cases', () => {
20+
expect(isHarshad(0)).toBe(false)
21+
expect(isHarshad(-18)).toBe(false)
22+
expect(isHarshad(1)).toBe(true)
23+
expect(isHarshad(10)).toBe(true)
24+
})
25+
26+
test('Input validation', () => {
27+
expect(isHarshad(18.5)).toBe(false)
28+
expect(isHarshad(null)).toBe(false)
29+
expect(isHarshad(undefined)).toBe(false)
30+
})
31+
})

0 commit comments

Comments
 (0)