The following iterative sequence is defined for the set of positive integers:
Which starting number, under one million, produces the longest chain?
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:n --> 3n + 1 (n is odd)
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 index+=1 counter*=2 end (MAX_NUM-1).downto(2) do |num| if n[num] next end rolling = num sequence = 0 while !n[rolling] if rolling % 2 == 0 rolling = rolling/2 else rolling = 3*rolling + 1 end sequence+=1 end n[num] = sequence + n[rolling] end puts "The maximum chained number is #{n.index(n.max)}"
Hover here to see the solution
Cheers!!
Bragaadeesh
No comments:
Post a Comment