Created
February 12, 2019 21:07
-
-
Save vcpablo/76364ff4dc3425442b6b81f00499a781 to your computer and use it in GitHub Desktop.
Collatz Conjecture - Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Standalone Collatz Conjecture function (https://en.wikipedia.org/wiki/Collatz_conjecture) | |
const collatz = (input) => { | |
let result = []; | |
let value = input; | |
while(value != 1) { | |
value = (value % 2 === 0) ? value / 2 : value * 3 + 1; | |
result.push(value) | |
} | |
return result; | |
}; | |
// Returns some information about the number that generates the bigger sequence of integers | |
const collatzAnalysis = function(input) { | |
if(!input || isNaN(input)) { | |
throw new Error('Input parameter must be a number'); | |
} | |
console.time('Time spent to calculate Collatz'); | |
// Variables declarations | |
var value = 0, | |
number = input, | |
biggestSequence, | |
items = {}, | |
totalItems = 0; | |
// Iterates over the input value example: if input = 1000, goes from 1000, 998, 997 ... until 2 | |
while(input != 1) { | |
value = input; | |
biggestSequence = 0; | |
while(value != 1) { | |
value = (value % 2 === 0) ? value / 2 : value * 3 + 1; | |
const index = input.toString(); | |
if(!items[index]) { | |
items[index] = []; | |
} | |
items[index].push(value); | |
biggestSequence++; | |
} | |
// Checks if the there is a bigger sequence than the stored previously | |
if(biggestSequence > totalItems) { | |
totalItems = biggestSequence; | |
number = input; | |
} | |
input--; | |
} | |
items = items[number.toString]; | |
console.timeEnd('Time spent to calculate Collatz'); | |
console.log(`Number ${number} produces the bigger sequence containing ${totalItems} items.`); | |
return { | |
number, // the number that returns the bigger sequence of numbers | |
items, // the greater sequence of numbers | |
totalItems // the size of the greater sequence of numbers | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment