Skip to content

Commit 6dfed7f

Browse files
feat: add happy number algorithm
1 parent 5c39e87 commit 6dfed7f

2 files changed

Lines changed: 84 additions & 0 deletions

File tree

‎Maths/HappyNumber.js‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @function isHappyNumber
3+
* @description A happy number is defined by the following process:
4+
* Starting with any positive integer, replace the number by the sum
5+
* of the squares of its digits, and repeat until the number equals 1
6+
* (where it will stay), or it loops endlessly in a cycle that does
7+
* not include 1.
8+
* @param {number} n - A positive integer
9+
* @returns {boolean} - True if n is a happy number, false otherwise
10+
* @see https://en.wikipedia.org/wiki/Happy_number
11+
* @example isHappyNumber(19) => true
12+
* @example isHappyNumber(7) => true
13+
* @example isHappyNumber(4) => false
14+
*/
15+
const isHappyNumber = (n) => {
16+
if (!Number.isInteger(n) || n < 1) {
17+
throw new TypeError('Input must be a positive integer')
18+
}
19+
const sumOfSquares = (num) =>
20+
String(num)
21+
.split('')
22+
.reduce((sum, d) => sum + Number(d) ** 2, 0)
23+
const seen = new Set()
24+
let current = n
25+
while (current !== 1) {
26+
if (seen.has(current)) return false
27+
seen.add(current)
28+
current = sumOfSquares(current)
29+
}
30+
return true
31+
}
32+
33+
export { isHappyNumber }

‎Maths/test/HappyNumber.test.js‎

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

0 commit comments

Comments
 (0)