From 45a273817238aa590f9d9ac79d84aa34eb3d9161 Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Sat, 7 Nov 2026 18:00:08 +0530 Subject: [PATCH] feat: add Padovan sequence algorithm --- Maths/PadovanSequence.js | 27 ++++++++++++++++ Maths/test/PadovanSequence.test.js | 51 ++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 Maths/PadovanSequence.js create mode 100644 Maths/test/PadovanSequence.test.js diff --git a/Maths/PadovanSequence.js b/Maths/PadovanSequence.js new file mode 100644 index 0000000000..1c1320d1ca --- /dev/null +++ b/Maths/PadovanSequence.js @@ -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 } diff --git a/Maths/test/PadovanSequence.test.js b/Maths/test/PadovanSequence.test.js new file mode 100644 index 0000000000..771eabb609 --- /dev/null +++ b/Maths/test/PadovanSequence.test.js @@ -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) + }) +})