Skip to content

Commit a0bc0b9

Browse files
authored
Merge pull request #34 from Chingye97/CollatSequence
Add CollatSequence.js
2 parents 3a83b3e + bad7993 commit a0bc0b9

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

Maths/CollatzSequence.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @function collatz
3+
* @description Applies the Collatz Sequence on a specified number.
4+
* The Collatz Sequence states that every natural number will always fall in a 1, 2, 4 loop when iterated under the following function:
5+
* If the number is even, divide by 2, and if its odd, multiply it by 3 and add 1.
6+
*
7+
* @parama {Integer} n The number to apply the Collatz Sequence to.
8+
*
9+
* @return An array of steps and the final result..
10+
*
11+
* @see (Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture)
12+
*
13+
* @example collatz(1) = { result: 1, steps: [] }
14+
* @example collatz(5) = { result: 1, steps: [16, 8, 4, 2, 1] }
15+
*/
16+
export function collatz (n) {
17+
const steps = []
18+
while (n !== 1) {
19+
if (n % 2 === 0) {
20+
n = n / 2
21+
} else {
22+
n = 3 * n + 1
23+
}
24+
25+
steps.push(n)
26+
}
27+
28+
return { result: n, steps: steps }
29+
}

Maths/test/CollatzSequence.test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { collatz } from '../CollatzSequence'
2+
3+
describe('The Collatz Sequence', () => {
4+
it('Should be 1', () => {
5+
expect(collatz(1)).toStrictEqual({ result: 1, steps: [] })
6+
expect(collatz(5)).toStrictEqual({ result: 1, steps: [16, 8, 4, 2, 1] })
7+
})
8+
})

0 commit comments

Comments
 (0)