Skip to content

Instantly share code, notes, and snippets.

@CarlosCD
Created May 20, 2015 01:14
Show Gist options
  • Save CarlosCD/c70e876851bf604c0413 to your computer and use it in GitHub Desktop.
Save CarlosCD/c70e876851bf604c0413 to your computer and use it in GitHub Desktop.
Power as addition and iteration
# 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