Last active
December 28, 2015 04:19
-
-
Save thiagokimo/7441754 to your computer and use it in GitHub Desktop.
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
require 'benchmark' | |
number = 257 | |
def power_of_2?(number) | |
return true if number == 1 | |
return false if number == 0 || number % 2 != 0 | |
power_of_2?(number / 2) | |
end | |
def plus_plus_power_of_2(n) | |
while not power_of_2?(n) | |
n +=1 | |
end | |
n | |
end | |
def next_power_of_2_with_log(n) | |
Math.log(n) / Math.log(2) % 1 == 0 | |
2**((Math.log(n) / Math.log(2)).ceil) | |
end | |
if plus_plus_power_of_2(number) == next_power_of_2_with_log(number) | |
Benchmark.bmbm(7) do |bm| | |
bm.report('plus plus') do | |
plus_plus_power_of_2(number) | |
end | |
bm.report('log') do | |
next_power_of_2_with_log(number) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment