Last active
September 1, 2018 00:57
-
-
Save amyhenning/834c337b11d4aad76df316e133947f4b to your computer and use it in GitHub Desktop.
Created a method to return the Collatz Sequence for a given n, then created a method to find the number with the longest Collatz Sqeuence between 1 and n
This file contains 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
def collatz(n) | |
# set an empty arry to contain the values of the sequence | |
ary = [] | |
# set initial index value to 0 | |
index = 0 | |
# start by pushing n into the array | |
ary.push(n) | |
# loop until the array includes the number 1, i.e. until the sequence is complete | |
until ary.include?(1) | |
# if the most recent number in the array is even, push a new value (half its value) into the array | |
if ary[index] % 2 == 0 | |
ary.push(ary[index] / 2) | |
# if the most recent number is odd, push a new value (3 times its value + 1) into the array | |
elsif ary[index] % 2 == 1 | |
ary.push(ary[index] * 3 + 1) | |
end | |
# increment the index value by 1 each loop | |
index += 1 | |
end | |
return ary.inspect | |
end | |
def longest_collatz(n) | |
longest_n = 0 | |
number_to_test = 1 | |
while number_to_test <= n | |
if collatz(number_to_test).length > longest_n | |
longest_n = number_to_test | |
number_to_test += 1 | |
else | |
number_to_test += 1 | |
end | |
end | |
return longest_n | |
end | |
puts collatz(3) | |
puts collatz(4) | |
puts collatz(7) | |
puts longest_collatz(1000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment