-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathCollatzConjecture.java
42 lines (38 loc) · 1.11 KB
/
CollatzConjecture.java
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
39
40
41
42
package com.thealgorithms.maths;
import java.util.ArrayList;
import java.util.List;
/**
* <a href="https://en.wikipedia.org/wiki/Collatz_conjecture">...</a>
*/
public class CollatzConjecture {
/**
* Calculate the next number of the sequence.
*
* @param n current number of the sequence
* @return next number of the sequence
*/
public int nextNumber(final int n) {
if (n % 2 == 0) {
return n / 2;
}
return 3 * n + 1;
}
/**
* Calculate the Collatz sequence of any natural number.
*
* @param firstNumber starting number of the sequence
* @return sequence of the Collatz Conjecture
*/
public List<Integer> collatzConjecture(int firstNumber) {
if (firstNumber < 1) {
throw new IllegalArgumentException("Must be a natural number");
}
ArrayList<Integer> result = new ArrayList<>();
result.add(firstNumber);
while (firstNumber != 1) {
result.add(nextNumber(firstNumber));
firstNumber = nextNumber(firstNumber);
}
return result;
}
}