Skip to Content
author's profile photo Ajit Kumar Panda

CCC2: Project Euler(14): Longest Collatz sequence Solution in Javascript

//Get Next term in Collatze Sequence
let getNextSeqTerm = (iCurrentNo)=>{return iCurrentNo % 2 == 0 ? (iCurrentNo / 2) : (3 * iCurrentNo) + 1 ;}

//Get no of terms in One Collatz Sequence
let getSeqTermsCnt = (iSeqStartNo)=>{
    var iTermsCnt = 2;
    do{
        iSeqStartNo = getNextSeqTerm(iSeqStartNo);
    }while(iSeqStartNo != 1 && ++iTermsCnt);
    return iTermsCnt;
};

//Print Longest Chain Starting No and Chain length
let printMaxSequence = (iUpperLimitStart)=>{
    let iMaxSeqStartNo = 0, iMaxSeqTermsCnt = 0;
    let sOutput = 'Under ' + iUpperLimitStart + ', ';
    do{
        let iSeqTermsCnt = getSeqTermsCnt(iUpperLimitStart);
        if(iSeqTermsCnt > iMaxSeqTermsCnt){
            iMaxSeqStartNo  = iUpperLimitStart;
            iMaxSeqTermsCnt     = iSeqTermsCnt;
        }
    }while(iUpperLimitStart-- !=1);
    sOutput = sOutput + 'Collatz sequence starting at ' + iMaxSeqStartNo + ' produces longest chain of ' + iMaxSeqTermsCnt + ' Terms';
    console.log(sOutput);
}

printMaxSequence(1000000);

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

0 Comments

    Add a comment
    10|10000 characters needed characters exceeded