Project Euler #14: Longest Collatz sequence

Sort by

recency

|

207 Discussions

|

  • + 0 comments

    My solution in Python worked for most of the test cases. Thing is, it didn't work on 4 of the test cases, and it seems like it just wants some hyper-optimizations that would end up being memory inefficient and weird. Seems like a pretty unfair set of test cases tbh.

  • + 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]]);
            }
        }
    }
    
  • + 0 comments

    out put for 20 terms is 18 please change it

  • + 1 comment

    Am I the only one facing problem with this code.... Starting number with the longest Collatz sequence up to 20 is 18 but why is the compiler expecting the answaer to be 19? 18>9>28>14>7>22>11>34>17>52>26>13>40>20>10>5>16>8>4>2>1

  • + 0 comments

    Can anyone help reduce runtime of this code

    #include <cmath>
    #include <cstdio>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int ColSeq(int x){
        int count = 0;
        while(x>1){
            if(x%2==0)
                x /= 2;
            else
                x = 3*x + 1;
            count++;
        }
        return count;
    }
    
    int main() {
        int t;
        scanf("%d",&t);
        while(t--){
            int n;
            scanf("%d",&n);
            int res;
            int max_res = 0;
            int max_x;
            for(int i=n;i>2;i++){
                res = ColSeq(i);
                if(res>max_res){
                    max_res = res;
                    max_x = i;
                }
            }
            printf("%d\n",max_x);
        }  
        return 0;
    }