Skip to content

Instantly share code, notes, and snippets.

@hyjk2000
Created June 2, 2020 02:48
Show Gist options
  • Save hyjk2000/d261fbe6051a2a4962f62013370f5a72 to your computer and use it in GitHub Desktop.
Save hyjk2000/d261fbe6051a2a4962f62013370f5a72 to your computer and use it in GitHub Desktop.
Exponentiation by Squaring
# frozen_string_literal: true
require 'benchmark'
def repeat_naive(str, num)
result = ''
str = str.to_s
num = num.to_i
while num.nonzero?
result += str
num -= 1
end
result
end
def repeat(str, num)
result = ''
str = str.to_s
num = num.to_i
while num.nonzero?
result += str if num.odd?
str += str
num /= 2
end
result
end
Benchmark.bmbm do |x|
x.report('näive') { repeat_naive('Hello!', 1000) }
x.report('EBS') { repeat('Hello!', 1000) }
x.report('*') { 'Hello!' * 1000 }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment