DebRaj
DebRaj

Reputation: 599

exponent formula in Ruby without using default operator

How can use methods to calculate exponent without using ** operator. Suppose method name calculate(a,b) where a is base and b is exponent value.

The value of a and b can be positive or negative integers, decimals, etc.

Thanks

Upvotes: 1

Views: 893

Answers (3)

floum
floum

Reputation: 1159

quite the same solution as Wand maker suggested, with different syntax for creating the Array :

Array.new(b, a).reduce(&:*)

Another solution using an enumerator (should be faster) :

b.times.reduce(1) { |r| r * a }

b.times returns an enumerator yielding the values 0 to b - 1 (resulting in b values)

the use of reduce with a block is best explained from its docs : http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-reduce

Upvotes: 2

pjs
pjs

Reputation: 19855

Would Math.exp(b * Math.log(a)) suit your needs? Note that while this works for non-integer a and b, it requires a > 0. It is also subject to the finite precision limitations of floating point arithmetic.


With the restriction that b is integer, the following recursive solution works and is O(log b), i.e., asymptotically faster than repeated multiplication:

def calculate(a, b)
  return 1.0 / calculate(a, -b) if b < 0
  if b == 0
    1
  elsif b.even?
    calculate(a * a, b / 2)
  else
    a * calculate(a, b - 1)
  end
end

The value of a can be integer or have decimals, and positive or negative. If you're worried about precision issues, you could also change the return statement to return Rational(1, calculate(a, -b)) if b < 0.

Upvotes: 3

Dani
Dani

Reputation: 1022

How about:

def calculate(a,b)
  b.times.reduce(1) { |acc, _| acc * a }
end

I think it's easy to read and it displays the exponent definition clearly.

Upvotes: 1

Related Questions