Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 1f2baec

Browse files
committedJan 24, 2025·
feat: add the Collatz conjecture
1 parent 19b4ced commit 1f2baec

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
 

‎maths/collatz_sequence.ts

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Generates the Collatz sequence for a given positive integer.
3+
*
4+
* The Collatz conjecture sequence is defined as follows:
5+
* - Start with any positive integer `n`.
6+
* - If `n` is even, divide it by 2.
7+
* - If `n` is odd, multiply it by 3 and add 1.
8+
* - Repeat the process with the new value of `n` until `n` equals 1.
9+
*
10+
* @param n - A positive integer to generate the Collatz sequence.
11+
* @throws {Error} - Throws an error if `n` is not a positive integer.
12+
* @returns {number[]} - The Collatz sequence starting from `n`.
13+
*
14+
* @example
15+
* collatzSequence(5); // Returns: [5, 16, 8, 4, 2, 1]
16+
* collatzSequence(10); // Returns: [10, 5, 16, 8, 4, 2, 1]
17+
*/
18+
export const collatzSequence = (n: number): number[] => {
19+
if (n <= 0 || !Number.isInteger(n)) {
20+
throw new Error('Sequence only defined for positive integers.')
21+
}
22+
23+
const result: number[] = []
24+
25+
while (n !== 1) {
26+
result.push(n)
27+
if (n % 2 === 0) {
28+
n /= 2
29+
} else {
30+
n = n * 3 + 1
31+
}
32+
}
33+
34+
result.push(1)
35+
return result
36+
}

‎maths/test/collatz_sequence.test.ts

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { collatzSequence } from '../collatz_sequence'
2+
3+
describe('collatzSequence', () => {
4+
test('should generate the correct Collatz sequence for n = 5', () => {
5+
const result = collatzSequence(5)
6+
expect(result).toEqual([5, 16, 8, 4, 2, 1])
7+
})
8+
9+
test('should generate the correct Collatz sequence for n = 1', () => {
10+
const result = collatzSequence(1)
11+
expect(result).toEqual([1])
12+
})
13+
14+
test('should handle large inputs correctly (n = 27)', () => {
15+
const result = collatzSequence(27)
16+
// The exact sequence for n = 27 is very long; check key parts
17+
expect(result[0]).toBe(27)
18+
expect(result[result.length - 1]).toBe(1)
19+
expect(result.length).toBeGreaterThan(100)
20+
})
21+
22+
test('should throw an error for n = 0', () => {
23+
expect(() => collatzSequence(0)).toThrow(
24+
'Sequence only defined for positive integers.'
25+
)
26+
})
27+
28+
test('should throw an error for negative inputs (n = -5)', () => {
29+
expect(() => collatzSequence(-5)).toThrow(
30+
'Sequence only defined for positive integers.'
31+
)
32+
})
33+
34+
test('should throw an error for non-integer inputs (n = 5.5)', () => {
35+
expect(() => collatzSequence(5.5)).toThrow(
36+
'Sequence only defined for positive integers.'
37+
)
38+
})
39+
})

0 commit comments

Comments
 (0)
Please sign in to comment.