Skip to content

Commit ddfea35

Browse files
feat: add Jacobsthal number algorithm
1 parent 5c39e87 commit ddfea35

2 files changed

Lines changed: 74 additions & 0 deletions

File tree

‎Maths/JacobsthalNumber.js‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function jacobsthalNumber
3+
* @description Jacobsthal numbers are a sequence where each number is
4+
* the sum of the previous number and twice the number before that.
5+
* Sequence: 0, 1, 1, 3, 5, 11, 21, 43, 85, 171...
6+
* @param {number} n - The position in the Jacobsthal sequence (0-indexed)
7+
* @returns {number} - The nth Jacobsthal number
8+
* @see https://en.wikipedia.org/wiki/Jacobsthal_number
9+
* @example jacobsthalNumber(0) => 0
10+
* @example jacobsthalNumber(4) => 5
11+
* @example jacobsthalNumber(6) => 21
12+
*/
13+
const jacobsthalNumber = (n) => {
14+
if (!Number.isInteger(n) || n < 0) {
15+
throw new TypeError('Input must be a non-negative integer')
16+
}
17+
if (n === 0) return 0
18+
if (n === 1) return 1
19+
let a = 0
20+
let b = 1
21+
for (let i = 2; i <= n; i++) {
22+
;[a, b] = [b, b + 2 * a]
23+
}
24+
return b
25+
}
26+
27+
export { jacobsthalNumber }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { jacobsthalNumber } from '../JacobsthalNumber.js'
2+
3+
describe('jacobsthalNumber', () => {
4+
test('jacobsthalNumber(0) returns 0', () => {
5+
expect(jacobsthalNumber(0)).toBe(0)
6+
})
7+
8+
test('jacobsthalNumber(1) returns 1', () => {
9+
expect(jacobsthalNumber(1)).toBe(1)
10+
})
11+
12+
test('jacobsthalNumber(2) returns 1', () => {
13+
expect(jacobsthalNumber(2)).toBe(1)
14+
})
15+
16+
test('jacobsthalNumber(3) returns 3', () => {
17+
expect(jacobsthalNumber(3)).toBe(3)
18+
})
19+
20+
test('jacobsthalNumber(4) returns 5', () => {
21+
expect(jacobsthalNumber(4)).toBe(5)
22+
})
23+
24+
test('jacobsthalNumber(5) returns 11', () => {
25+
expect(jacobsthalNumber(5)).toBe(11)
26+
})
27+
28+
test('jacobsthalNumber(6) returns 21', () => {
29+
expect(jacobsthalNumber(6)).toBe(21)
30+
})
31+
32+
test('jacobsthalNumber(7) returns 43', () => {
33+
expect(jacobsthalNumber(7)).toBe(43)
34+
})
35+
36+
test('jacobsthalNumber(8) returns 85', () => {
37+
expect(jacobsthalNumber(8)).toBe(85)
38+
})
39+
40+
test('throws TypeError for negative input', () => {
41+
expect(() => jacobsthalNumber(-1)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for float input', () => {
45+
expect(() => jacobsthalNumber(1.5)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)