Skip to content

Commit 372cdf1

Browse files
feat: add Sylvester sequence algorithm
1 parent 5c39e87 commit 372cdf1

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎Maths/SylvesterSequence.js‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @function sylvesterSequence
3+
* @description Sylvester's sequence is an integer sequence where each
4+
* term is the product of all previous terms plus one.
5+
* Sequence: 2, 3, 7, 43, 1807, 3263443...
6+
* @param {number} n - Number of terms to generate (1-indexed count)
7+
* @returns {number[]} - Array of first n terms of Sylvester's sequence
8+
* @see https://en.wikipedia.org/wiki/Sylvester%27s_sequence
9+
* @example sylvesterSequence(1) => [2]
10+
* @example sylvesterSequence(4) => [2, 3, 7, 43]
11+
*/
12+
const sylvesterSequence = (n) => {
13+
if (!Number.isInteger(n) || n < 1) {
14+
throw new TypeError('Input must be a positive integer')
15+
}
16+
const sequence = [2]
17+
for (let i = 1; i < n; i++) {
18+
const prev = sequence[i - 1]
19+
sequence.push(sequence.reduce((product, num) => product * num, 1) + 1)
20+
}
21+
return sequence
22+
}
23+
24+
export { sylvesterSequence }
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { sylvesterSequence } from '../SylvesterSequence.js'
2+
3+
describe('sylvesterSequence', () => {
4+
test('sylvesterSequence(1) returns [2]', () => {
5+
expect(sylvesterSequence(1)).toEqual([2])
6+
})
7+
8+
test('sylvesterSequence(2) returns [2, 3]', () => {
9+
expect(sylvesterSequence(2)).toEqual([2, 3])
10+
})
11+
12+
test('sylvesterSequence(3) returns [2, 3, 7]', () => {
13+
expect(sylvesterSequence(3)).toEqual([2, 3, 7])
14+
})
15+
16+
test('sylvesterSequence(4) returns [2, 3, 7, 43]', () => {
17+
expect(sylvesterSequence(4)).toEqual([2, 3, 7, 43])
18+
})
19+
20+
test('sylvesterSequence(5) returns [2, 3, 7, 43, 1807]', () => {
21+
expect(sylvesterSequence(5)).toEqual([2, 3, 7, 43, 1807])
22+
})
23+
24+
test('sylvesterSequence returns correct length', () => {
25+
expect(sylvesterSequence(4)).toHaveLength(4)
26+
})
27+
28+
test('sylvesterSequence starts with 2', () => {
29+
expect(sylvesterSequence(3)[0]).toBe(2)
30+
})
31+
32+
test('throws TypeError for zero', () => {
33+
expect(() => sylvesterSequence(0)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for negative input', () => {
37+
expect(() => sylvesterSequence(-1)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float input', () => {
41+
expect(() => sylvesterSequence(1.5)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)