Created
May 20, 2015 01:14
-
-
Save CarlosCD/c70e876851bf604c0413 to your computer and use it in GitHub Desktop.
Power as addition and iteration
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
# Question from Quora.com: | |
# How do I write a program that computes "b" raised to power "n" using only addition and iteration? | |
# http://www.quora.com/Computer-Programming/How-do-I-write-a-program-that-computes-b-raised-to-power-n-using-only-addition-and-iteration | |
# My solution in Ruby: | |
def power(b, n) | |
result = 1 | |
n.times do | |
result = Array.new(b, result).reduce(:+).to_i | |
end | |
result | |
end | |
# Or an alternative solution, without Array and reduce: | |
def mult (a, b) | |
result = 0 | |
b.times{ result += a } | |
result | |
end | |
def power(b, n) | |
result = 1 | |
n.times{ result = mult(result, b) } | |
result | |
end | |
# Which can be combined as: | |
def power(b, n) | |
result = 1 | |
n.times do | |
subtotal = 0 | |
b.times{ subtotal += result } | |
result = subtotal | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment