-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollatz.js
More file actions
36 lines (30 loc) · 776 Bytes
/
Collatz.js
File metadata and controls
36 lines (30 loc) · 776 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
class Collatz {
constructor() {
this.calculatedNumbers = {};
}
getNumberOfIterations(valueInformed) {
if (valueInformed <= 0 || !Number.isInteger(valueInformed)) {
throw new Error('Only positive integers allowed');
}
let currentValue = valueInformed;
let count = 1;
while (currentValue > 1) {
currentValue = this.calculateSingleIteration(currentValue);
if (this.calculatedNumbers[currentValue]) {
count += this.calculatedNumbers[currentValue];
break;
}
count += 1;
}
this.calculatedNumbers[valueInformed] = count;
return count;
}
calculateSingleIteration(n) {
if (n % 2 === 0) {
return n / 2;
} else {
return n * 3 + 1;
}
}
}
module.exports = Collatz;