Project Euler #14: Longest Collatz sequence

  • + 0 comments
    import java.util.Scanner;
    
    public class Solution {
        public static long numState(long num) {
            long numState = 0;
            while (num != 1) {
                if (num % 2 == 0) {
                    num /= 2;
                } else {
                    num = 3 * num + 1;
                }
                numState++;
            }
            return numState;
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int t = scanner.nextInt();
            int[] arrInput = new int[t];
            int max = 0;
            for (int i = 0; i < t; i++) {
                arrInput[i] = scanner.nextInt();
                if (arrInput[i] > max) {
                    max = arrInput[i];
                }
            }
            long[] ans = new long[max + 1];
            long maxState = 1;
            long steps = 1;
            for (long j = 1; j <= max; j++) {
                long numState = numState(j);
                if (numState >= maxState) {
                    maxState = numState;
                    steps = j;
                }
                ans[(int) j] = steps;
            }
            for (int j = 0; j < t; j++) {
                System.out.println(ans[arrInput[j]]);
            }
        }
    }