From 372cdf1726778354b09d4ac2535b358020c4a2cd Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Sat, 7 Nov 2026 18:09:18 +0530 Subject: [PATCH] feat: add Sylvester sequence algorithm --- Maths/SylvesterSequence.js | 24 ++++++++++++++++ Maths/test/SylvesterSequence.test.js | 43 ++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 Maths/SylvesterSequence.js create mode 100644 Maths/test/SylvesterSequence.test.js diff --git a/Maths/SylvesterSequence.js b/Maths/SylvesterSequence.js new file mode 100644 index 0000000000..df974c5ab2 --- /dev/null +++ b/Maths/SylvesterSequence.js @@ -0,0 +1,24 @@ +/** + * @function sylvesterSequence + * @description Sylvester's sequence is an integer sequence where each + * term is the product of all previous terms plus one. + * Sequence: 2, 3, 7, 43, 1807, 3263443... + * @param {number} n - Number of terms to generate (1-indexed count) + * @returns {number[]} - Array of first n terms of Sylvester's sequence + * @see https://en.wikipedia.org/wiki/Sylvester%27s_sequence + * @example sylvesterSequence(1) => [2] + * @example sylvesterSequence(4) => [2, 3, 7, 43] + */ +const sylvesterSequence = (n) => { + if (!Number.isInteger(n) || n < 1) { + throw new TypeError('Input must be a positive integer') + } + const sequence = [2] + for (let i = 1; i < n; i++) { + const prev = sequence[i - 1] + sequence.push(sequence.reduce((product, num) => product * num, 1) + 1) + } + return sequence +} + +export { sylvesterSequence } diff --git a/Maths/test/SylvesterSequence.test.js b/Maths/test/SylvesterSequence.test.js new file mode 100644 index 0000000000..b848515f01 --- /dev/null +++ b/Maths/test/SylvesterSequence.test.js @@ -0,0 +1,43 @@ +import { sylvesterSequence } from '../SylvesterSequence.js' + +describe('sylvesterSequence', () => { + test('sylvesterSequence(1) returns [2]', () => { + expect(sylvesterSequence(1)).toEqual([2]) + }) + + test('sylvesterSequence(2) returns [2, 3]', () => { + expect(sylvesterSequence(2)).toEqual([2, 3]) + }) + + test('sylvesterSequence(3) returns [2, 3, 7]', () => { + expect(sylvesterSequence(3)).toEqual([2, 3, 7]) + }) + + test('sylvesterSequence(4) returns [2, 3, 7, 43]', () => { + expect(sylvesterSequence(4)).toEqual([2, 3, 7, 43]) + }) + + test('sylvesterSequence(5) returns [2, 3, 7, 43, 1807]', () => { + expect(sylvesterSequence(5)).toEqual([2, 3, 7, 43, 1807]) + }) + + test('sylvesterSequence returns correct length', () => { + expect(sylvesterSequence(4)).toHaveLength(4) + }) + + test('sylvesterSequence starts with 2', () => { + expect(sylvesterSequence(3)[0]).toBe(2) + }) + + test('throws TypeError for zero', () => { + expect(() => sylvesterSequence(0)).toThrow(TypeError) + }) + + test('throws TypeError for negative input', () => { + expect(() => sylvesterSequence(-1)).toThrow(TypeError) + }) + + test('throws TypeError for float input', () => { + expect(() => sylvesterSequence(1.5)).toThrow(TypeError) + }) +})