Behold: The Collatz Conjecture Library!

You might have read my post on the Collatz Conjecture. If you didn’t, you can read it with this link. If you read it, you know I talked about a cool problem called the Collatz Conjecture, and also showed you a piece of code I made. Well, I updated the code, into a library of functions meant for calculating numbers on the Collatz Conjecture. I have the Gist right here:

class Collatz
def initialize(num)
@num = num
@steps = find_steps(num)
end
def steps
@steps
end
def number
@num
end
def find_steps(num)
counter = 1
if num <= 0
raise "This program does not accept negative numbers."
end
#checking if it is a float
unless num.to_i == num
raise "This program does not accept floats."
end
num = num.to_i
orig_num = num
loop do
if num.even?
num /= 2
else
num = 3*num + 1
end
if 1 == num
return counter
break
else
counter += 1
end
end
end
#static methods
def self.find_max_steps(limit)
objs = []
limit.times do |idx|
objs << Collatz.new(idx+1)
end
#finding max steps
return objs.max{ |a,b| a.steps <=> b.steps }
end
def self.find_smallest_steps(coef)
idx = 1
loop do
collatz = Collatz.new(idx)
if collatz.steps > coef * idx
return collatz
end
idx += 1
end
end
end
obj = Collatz.find_max_steps(100)
puts "it took #{obj.steps} steps to reach from #{obj.number} to 1 which is maximum steps for a number under 100"
obj = Collatz.find_smallest_steps(3)
puts "#{obj.number} is the smallest number to have number of steps (#{obj.steps}) more than 3 times the number"

There is a class called Collatz, and inside it 6 methods. The first two are simply for returning variables, nothing cool. The most important method inside it is find_steps, which calculates the amount of steps it takes to get from a certain number to 1. The find_max_steps method sees which number from a range of 1 to the method argument has the most steps. The final method, find_smallest steps, returns the smallest number whose steps are more than itself times the argument.

I’m thinking of posting this as a GitHub project, once I improve it. If you have any suggestions for more methods, or just to increase quality, please write in the comments. Thanks!

One thought on “Behold: The Collatz Conjecture Library!

Leave a Reply to Sergey Cancel reply

Your email address will not be published. Required fields are marked *