Enter the number under which you want to find out the longest Collatz chain, in the input box and press the Start Processing button. It is defaulted to 1 million as per the challenge question.
sap.ui.getCore().attachInit(function() {
"use strict";
sap.ui.controller("MyController", {
onInit: function() {
//The answer to the challenge is 837799, which is calculated by below
//function
this.process();
},
process: function() {
var startTime = window.performance.now();
var result = this.getMaxCollatzUnder(this.getView().byId("_idNumber").getValue());
var endTime = window.performance.now();
var data = result.split('/');
var perf = endTime - startTime;
this.getView().byId("maxNum").setText(" : " + data[0]);
this.getView().byId("maxSteps").setText(" : " + data[1]);
this.getView().byId("timeTaken").setText(" : " + perf + " ms");
},
getMaxCollatzUnder: function(k) {
//Find which is the max number below 1000000, which has max steps for Collatz sequence
var numOfSteps = 1;
var maxSteps = 0,
maxNumber = 1;
var hashTabUsed = 0;
var cacheHashTab = new Object(); //Hash table to keep caching data
var num = 1;
var currNum = 1;
//For each number from 1 till input
while (currNum <= k) {
num = currNum;
numOfSteps = 1;
//calculate Collatz Steps
while (num !== 1) {
//Check if cache already knows the number of steps for this number
if (cacheHashTab.hasOwnProperty(num)) {
numOfSteps = numOfSteps + cacheHashTab[num] - 1;
hashTabUsed++;
break;
}
if (num % 2 === 0) {
num = num / 2;
} else {
num = (3 * num + 1);
}
numOfSteps++;
}
//Keep caching the number of steps for further use
cacheHashTab[currNum] = numOfSteps;
if (numOfSteps > maxSteps) {
maxSteps = numOfSteps;
maxNumber = currNum;
}
currNum++;
}
var result = maxNumber + '/' +...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!