Skip to Content
author's profile photo Rahul Gupta

CCC2 Longest Collatz (Euler 14) Solution using Recurssion and Functional Programming in JavaScript

const longestChainNum = (MAX_NUMBER = 1e6) => {
    const dictionary = {};           // Stored the calculated values                               
    const collatzSequence = n =>     // Recursive Fn to get seq                                      
        dictionary[n] === undefined  // No Val in Dictionary                              
        ? n === 1                    // Last call in recursion                         
            ? (dictionary[n] = 1)                                     
            : n % 2 === 0            // Check for even or odd                         
                ? (dictionary[n] = collatzSequence(n / 2) + 1)             
// Add 2 to the seq. since odd number will always result in even (can avoid 1 un-necesaary Fn call) 
                : (dictionary[n] = collatzSequence((3 * n + 1) / 2) + 2)  
        : dictionary[n];

      return ((i = 1) => {          // IIFE for loop & return result                                 
        let largestValue = 0,
            number       = 0;
        while (i++ < MAX_NUMBER) 
            number = collatzSequence(i) > largestValue 
                     ? (largestValue = collatzSequence(i)) && i 
                     : number;
        return number;
      })();
};

console.log(longestChainNum());      // Output the largest number under 1 million - 837799    

Above code produces the answer - 837799


Thanks,

Rahul

* Please Login or Register to Comment on or Follow discussions.

0 Comments

    Add a comment
    10|10000 characters needed characters exceeded