Created
May 27, 2011 21:30
-
-
Save johana-star/996221 to your computer and use it in GitHub Desktop.
Euler Project Problem #014
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
# Solution to Project Euler's fourteenth problem | |
# http://projecteuler.net/index.php?section=problems&id=14 | |
# Find the longest Collatz conjecture chain starting with a number under one million. | |
def find_lengths(ceiling=999999) | |
numbers = (1..ceiling).to_a | |
terms = Array.new(ceiling, 1) | |
numbers.each_with_index do |n, i| | |
if n%16==15 or n%16==7 or n%16==11 or n%16==9 or n%16==1 then #to improve the search speed, filter out all hexadecimal numbers not ending in 15, 7, 11, 9, or 1, in that order for all numbers % 16 greater than 64, the remainder is either 15, 7, 11, 9, or 1, with a greater frequency on the fifteens and then the sevens. | |
until n == 1 | |
if n.even? then | |
n = n/2 | |
terms[i] +=1 | |
else | |
n = 3*n+1 | |
terms[i] +=1 | |
end | |
end | |
end | |
end | |
return terms | |
end | |
def index_of_longest(lengths) | |
longest, index = 0, -1 | |
lengths.each_with_index do |l, i| | |
if longest < l then longest = l; index = i; p index + 1 end | |
end | |
return index | |
end | |
a = Time.new | |
lengths = find_lengths | |
index = index_of_longest(lengths) | |
p index + 1 | |
b = Time.new - a | |
p b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment