Skip to content

Commit 45a2738

Browse files
feat: add Padovan sequence algorithm
1 parent 5c39e87 commit 45a2738

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

‎Maths/PadovanSequence.js‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function padovanSequence
3+
* @description The Padovan sequence is similar to Fibonacci but each
4+
* number is the sum of the second and third preceding numbers.
5+
* Sequence: 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16...
6+
* @param {number} n - The position in the Padovan sequence (0-indexed)
7+
* @returns {number} - The nth Padovan number
8+
* @see https://en.wikipedia.org/wiki/Padovan_sequence
9+
* @example padovanSequence(0) => 1
10+
* @example padovanSequence(5) => 3
11+
* @example padovanSequence(7) => 5
12+
*/
13+
const padovanSequence = (n) => {
14+
if (!Number.isInteger(n) || n < 0) {
15+
throw new TypeError('Input must be a non-negative integer')
16+
}
17+
if (n === 0 || n === 1 || n === 2) return 1
18+
let a = 1
19+
let b = 1
20+
let c = 1
21+
for (let i = 3; i <= n; i++) {
22+
;[a, b, c] = [b, c, a + b]
23+
}
24+
return c
25+
}
26+
27+
export { padovanSequence }

‎Maths/test/PadovanSequence.test.js‎

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

0 commit comments

Comments
 (0)