Skip to content

Instantly share code, notes, and snippets.

@ClearNB
Created January 8, 2019 08:17
Show Gist options
  • Save ClearNB/eb411e07cbfb04e124b9a16f622d7bb3 to your computer and use it in GitHub Desktop.
Save ClearNB/eb411e07cbfb04e124b9a16f622d7bb3 to your computer and use it in GitHub Desktop.
Longest Collatz sequence (Java 8 ver) Sample by ClearNB
import java.util.*;
public class Solution {
public static int cnt = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> s = getMayors(5000000);
int T = sc.nextInt();
for(int i = 0; i < T; i++) {
int N = sc.nextInt();
System.out.println(s.get(N - 1));
}
}
static List<Integer> getMayors(long n) {
List<Integer> s = new ArrayList<Integer>();
List<Integer> m = new ArrayList<Integer>();
int ms = 0;
int cd = 1;
for(int i = 1; i <= n; i++) {
cnt = 0;
getSequence(i, m);
m.add(cnt);
if(cnt >= ms) {
cd = i;
ms = cnt;
}
s.add(cd);
}
return s;
}
static void getSequence(long n, List<Integer> s) {
if(n != 1) {
if(s.size() >= n) {
cnt += s.get((int) n - 1);
} else {
if((n % 2) == 0) {
cnt++;
getSequence(n / 2, s);
} else {
cnt++;
getSequence((3 * n) + 1, s);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment