I would say it is node.js task since there was nothing about presentation in requirements. Rather simple... ;)
/*
Every given number have one postion on calculated sequence,
that is constant, for all posible sequences, therefore it can be reused.
*/
let positions = {}
const isOdd = x => x & 1
const nextN = n => isOdd(n) ? 3 * n + 1 : n / 2
const calculateSequence = n => {
let sequence = [n]
do {
n = nextN(n)
sequence.push(n)
// If n positioned already - not need to continue
if (positions[n] !== undefined) {
return sequence
break
}
} while (n != 1)
return sequence
}
const mapSequence = sequence => {
let i = 1
for (var n of sequence.reverse()) {
// Sequence is compleate and new
if (n == 1) {
positions[n] = i
} else {
// Number from sequence is positioned
if (i == 1) {
// So we just take already calculated position and continue
i = positions[n]
} else {
positions[n] = i
}
}
i++
}
}
const highestLengthFromCollatzConjecture = limit => {
for (var j = limit; j > 0; j--) {
let sequence = calculateSequence(j)
mapSequence(sequence)
}
let highestLength = 0
let startingNumber = 1
for (var k = limit; k > 0; k--) {
if (positions[k] > highestLength) {
startingNumber = k
highestLength = positions[k]
}
}
return [startingNumber, highestLength]
}
const [startingNumber, highestLength] = highestLengthFromCollatzConjecture(1000000)
console.log(`Starting Number: ${startingNumber} had highest length of ${highestLength}.`)