Skip to content

Instantly share code, notes, and snippets.

@drhuffman12
Created October 17, 2016 20:36
Show Gist options
  • Save drhuffman12/dfc07ddfd1e0bf9b245c53194d1fcbec to your computer and use it in GitHub Desktop.
Save drhuffman12/dfc07ddfd1e0bf9b245c53194d1fcbec to your computer and use it in GitHub Desktop.
Check if numbers are power of 2
# based on http://stackoverflow.com/questions/29718767/check-if-array-elements-are-power-of-two
require 'benchmark'
class Po2
def self.via_to_s(n)
(n.to_s(2) =~ /^10*$/) ? 0 : 1 # faster for more than about 100 numbers
end
def self.via_log(n)
(Math.log2(2**n+1) % 1) == 0 # faster for less than about 100 numbers
end
end
# data = [0,1,2,3,4,5,6,7,8,9,10]
# data = 10.times.to_a
# data = 100.times.to_a
data = 1000.times.to_a
data00001 = [0,1,2,3,4,5,6,7,8,9]
data00010 = [10,11,12,13,14,15,16,17,18,19]
data00100 = [100,101,102,103,104,105,106,107,108,109]
data01000 = [1000,1001,1002,1003,1004,1005,1006,1007,1008,1009]
data10000 = [10000,10001,10002,10003,10004,10005,10006,10007,10008,10009]
puts data.inspect
puts data.collect {|n| Po2.via_to_s(n)}.inspect
puts data.collect {|n| Po2.via_log(n)}.inspect
Benchmark.bm do |x|
x.report('po2_to_s') { data.collect {|n| Po2.via_to_s(n)} }
x.report('po2_log') { data.collect {|n| Po2.via_log(n)} }
end;nil
Benchmark.bm do |x|
[data00001,data00010,data00100,data01000,data10000].each do |d|
x.report("po2_to_s #{d}") { d.collect {|n| Po2.via_to_s(n)} }
x.report("po2_log #{d}") { d.collect {|n| Po2.via_log(n)} }
end
end;nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment