I am pretty new to solving algorithms so bear with me.
I've solved the Collatz sequence for max length of 1,000,000 but I want to make it more efficient by using a hashtable to look up keys that already exist in order make the function faster. However, I know I'm doing something wrong because it's supposed to take only about 1-2 seconds to run number = 1,000,000, but it's still taking 9-10 seconds to run. I'm pretty new to using hashtables in algorithms so can someone please tell me what I'm doing wrong here in my method?
Much appreciated!
def collatz(n)
chain = 1
until n == 1
n = (n.even?) ? (n/2) : (n*3+1)
chain += 1
end
chain
end
def longest_chain2(number)
cache = { 1 => 1 }
start_num = 1
longest = 1
while start_num < number
chain = cache[start_num]
if chain > longest
longest = chain
longest_start = start_num
end
start_num += 1
cache[start_num] = collatz(start_num)
end
return longest_start
end
puts longest_chain2(1000000)