There are 2 approaches one with cache and without cache. as caching is efficient for this challenge, but need to can easily break with huge number will limited memory capacity.
Approach:
Posting both approach, with cache and without cache.
With Cache:
Executable Code: https://repl.it/@girishnvmg/CollatzSequenceWithCache
console.log("SAP CCD-2: Longest Collatz sequence with cache") let maxNumber = 1000000; let cache = new Array(maxNumber + 1).fill(false); let processStartTime = process.hrtime(); let maxStep = 0; let maxValue = 0; cache[0] = cache[1] = 1; let calcSteps = (value) => { let val = value let step = 0; while(value >= val) { if(value & 1) { value = 3 * value + 1; step ++ } value = value >>> 1; step += 1; } if((step + cache[value]) > maxStep) { maxStep = step + cache[value]; maxValue = val; } return step + cache[value]; } for(let i = 2; i < maxNumber; i++) cache[i] = calcSteps(i); console.log(`Value: ${maxValue} - Steps: ${maxStep}. [Time Taken : ${process.hrtime(processStartTime)[1] /1000000 }ms]`)
Without Cache
Executable Link: https://repl.it/@girishnvmg/CollatzSequenceWithoutCache
console.log("SAP CCD-2: Longest Collatz sequence without cache") let maxNumber = 1000000; let processStartTime = process.hrtime(); let maxStep = 0; let maxValue = 0; let i = 1 let calcSteps = (value) => { let val = value; let step = 1; while (value != 1) { if(value & 1) { value = 3 * value + 1; step ++ } value = value >>> 1; step += 1; } if(maxStep < step) { maxStep = step; maxValue = val; } } while(i <= maxNumber) calcSteps(i++); console.log(`Value: ${maxValue} - Steps: ${maxStep}. [Time Taken : ${process.hrtime(processStartTime)[1] /1000000 }ms]`)
#Stay Healthy, #Stay Safe.