21 August 2010

Project Euler : Find the longest sequence using a starting number under one million.

Problem 14

The following iterative sequence is defined for the set of positive integers:
n --> n/2 (n is even)
n --> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 --> 40 --> 20 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.

Solution (in Ruby)

In order to solve this problem, we first need to find a pattern by attacking in the reverse order. If you could see if the number gotten is a power of two, it will diminish all the way upto 1. So its wiser to store their frequency (power of 2 numbers) first in the array. The next interesting property is that if you find the chain count for a number you do not want to find that again. Combining these two properties, we can very well get a linear solution for the input count of 1 million solving the problem within seconds.

MAX_NUM = 1000000
n = Array.new(MAX_NUM)
n[0] = 0
n[1] = 1
counter = 1
index = 1
while (counter < MAX_NUM)
  n[counter] = index
(MAX_NUM-1).downto(2) do |num|
  if n[num]
  rolling = num
  sequence = 0
  while !n[rolling]
    if rolling % 2 == 0
      rolling = rolling/2
      rolling = 3*rolling + 1
  n[num] = sequence + n[rolling]
puts "The maximum chained number is #{n.index(n.max)}"

Hover here to see the solution


No comments: