-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollatzConjecture.js
More file actions
38 lines (29 loc) · 1020 Bytes
/
Copy pathcollatzConjecture.js
File metadata and controls
38 lines (29 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Description:
// The Collatz conjecture (also known as 3n+1 conjecture) is a conjecture that applying the following algorithm to any number we will always eventually reach one:
// [This is writen in pseudocode]
// if(number is even) number = number / 2
// if(number is odd) number = 3*number + 1
// #Task
// Your task is to make a function hotpo that takes a positive n as input and returns the number of times you need to perform this algorithm to get n = 1.
// #Examples
// hotpo(1) returns 0
// (1 is already 1)
// hotpo(5) returns 5
// 5 -> 16 -> 8 -> 4 -> 2 -> 1
// hotpo(6) returns 8
// 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
// hotpo(23) returns 15
// 23 -> 70 -> 35 -> 106 -> 53 -> 160 -> 80 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
//one way
const hotpo = (n, acc = 0) =>
n <= 1 ? acc : hotpo(n % 2 === 0 ? n / 2 : 3 * n + 1, acc + 1)
//another way
let hotpoh = n => {
if (n == 0) return 0;
let c = 0;
while (n > 1) {
n = (n % 2 ? 3 * n + 1 : n / 2);
c++;
}
return c;
}