Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Maths/PadovanSequence.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @function padovanSequence
* @description The Padovan sequence is similar to Fibonacci but each
* number is the sum of the second and third preceding numbers.
* Sequence: 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16...
* @param {number} n - The position in the Padovan sequence (0-indexed)
* @returns {number} - The nth Padovan number
* @see https://en.wikipedia.org/wiki/Padovan_sequence
* @example padovanSequence(0) => 1
* @example padovanSequence(5) => 3
* @example padovanSequence(7) => 5
*/
const padovanSequence = (n) => {
if (!Number.isInteger(n) || n < 0) {
throw new TypeError('Input must be a non-negative integer')
}
if (n === 0 || n === 1 || n === 2) return 1
let a = 1
let b = 1
let c = 1
for (let i = 3; i <= n; i++) {
;[a, b, c] = [b, c, a + b]
}
return c
}

export { padovanSequence }
51 changes: 51 additions & 0 deletions Maths/test/PadovanSequence.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { padovanSequence } from '../PadovanSequence.js'

describe('padovanSequence', () => {
test('padovanSequence(0) returns 1', () => {
expect(padovanSequence(0)).toBe(1)
})

test('padovanSequence(1) returns 1', () => {
expect(padovanSequence(1)).toBe(1)
})

test('padovanSequence(2) returns 1', () => {
expect(padovanSequence(2)).toBe(1)
})

test('padovanSequence(3) returns 2', () => {
expect(padovanSequence(3)).toBe(2)
})

test('padovanSequence(4) returns 2', () => {
expect(padovanSequence(4)).toBe(2)
})

test('padovanSequence(5) returns 3', () => {
expect(padovanSequence(5)).toBe(3)
})

test('padovanSequence(6) returns 4', () => {
expect(padovanSequence(6)).toBe(4)
})

test('padovanSequence(7) returns 5', () => {
expect(padovanSequence(7)).toBe(5)
})

test('padovanSequence(8) returns 7', () => {
expect(padovanSequence(8)).toBe(7)
})

test('padovanSequence(9) returns 9', () => {
expect(padovanSequence(9)).toBe(9)
})

test('throws TypeError for negative input', () => {
expect(() => padovanSequence(-1)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => padovanSequence(1.5)).toThrow(TypeError)
})
})
Loading