-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLongestCollatzSequence.java
51 lines (47 loc) · 1.47 KB
/
LongestCollatzSequence.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
43
44
45
46
47
48
49
50
51
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
List<Integer> solution = getGreater((long) 5000000);
int t = in.nextInt();
for(int i = 0; i<t; i++){
int n = in.nextInt();
System.out.println(solution.get(n-1));
}
}
static List<Integer> getGreater(long n){
List<Integer> solution = new ArrayList<Integer>();
List<Integer> Greater = new ArrayList<Integer>();
int num = 0;
int number = 1;
for(int i = 1; i<=n; i++){
cont = 0;
getSequence(i,Greater);
Greater.add(cont);
if(cont>=num){
number = i;
num = cont;
}
solution.add(number);
}
return solution;
}
public static int cont = 0;
static void getSequence(long n, List<Integer> solution){
if(n!=1){
if(solution.size()>=n){
cont += solution.get((int) n-1);
}else{
if(n%2==0){
cont++;
getSequence(n/2,solution);
}else{
cont++;
getSequence((3*n)+1,solution);
}
}
}
}
}