Skip to content

Instantly share code, notes, and snippets.

@thiagokimo
Last active December 28, 2015 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagokimo/7441754 to your computer and use it in GitHub Desktop.
Save thiagokimo/7441754 to your computer and use it in GitHub Desktop.
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