Created
June 2, 2020 02:48
-
-
Save hyjk2000/d261fbe6051a2a4962f62013370f5a72 to your computer and use it in GitHub Desktop.
Exponentiation by Squaring
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
# 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