I have the following method that I wrote for Project Euler - Problem 36. All it does is add up all the numbers less than 1,000,000 that are palindromes in both base 10 and base 2.
def problem_36
(1...1_000_000).select do |n|
n.to_s == n.to_s.reverse && n.to_s(2) == n.to_s(2).reverse
end
end
Now, this works and gives the correct result in just over 1 second. I wanted to get it under 1 second, so I decided I would reduce the number of times I was converting numbers to strings. So I made the following changes:
def problem_36
(1...1_000_000).select do |n|
base10 = n.to_s
base2 = n.to_s(2)
base10 == base10.reverse && base2 == base2.reverse
end
end
The trouble is, this version actually runs about 50% slower than the original. So the question is this: is it really that slow to allocate those two variables? Or is Ruby optimizing the chained method calls?
In this line
n.to_s == n.to_s.reverse && n.to_s(2) == n.to_s(2).reverse
the second part is not executed if the first part is false
(Ruby's &&
operator short-circuits, unlike its &
counterpart). That saves a lot of calls to to_s(2)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With