Created
March 9, 2012 21:23
-
-
Save pullmonkey/2008772 to your computer and use it in GitHub Desktop.
euler_problem_14
This file contains hidden or 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
| $chain_lengths = {:largest_num => 0, :largest_chain => 0, 1 => 1, 2 => 2} | |
| def get_chain_length_for(n) | |
| return $chain_lengths[n] if $chain_lengths.has_key?(n) | |
| next_n = 3 * n + 1 if n.odd? | |
| next_n = n / 2 if n.even? | |
| return ($chain_lengths[next_n] = get_chain_length_for(next_n)) + 1 | |
| end | |
| (2..999999).each do |x| | |
| len = get_chain_length_for(x) | |
| $chain_lengths[x] = len | |
| if len > $chain_lengths[:largest_chain] | |
| $chain_lengths[:largest_num] = x | |
| $chain_lengths[:largest_chain] = len | |
| end | |
| end | |
| puts $chain_lengths[:largest_num] | |
| puts $chain_lengths[:largest_chain] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment