Machiavellie
Machiavellie

Reputation: 61

Ruby exponentiation warning for large numbers

I am working on a problem in Ruby. The function called last_digit takes in two integers. The first integer is then raised to the power of the second integer. The function must return the last digit of that integer after this calculation has been completed.For example, if the first integer was 2 and the second 4, then the function would do 2 ** 4, which equals 16 and then return the last digit of that number, which is 6.

I have written a ruby function to do this but once the numbers get too large I believe the result defaults to infinity and my function returns the wrong answer of 0. My ide also brings up the following warning:

warning: in a**b, b may be too big 469Infinity

My code followed by my test cases can be seen below:

def last_digit(n1, n2)
  num = n1 ** n2
  if num == 0
    return print 1
  end
  return print num.to_s[-1].to_i
end

last_digit(4, 1)                # returns 4
last_digit(4, 2)                # returns 6
last_digit(9, 7)                # returns 9
last_digit(10, 10 ** 10)        # return 0
last_digit(2 ** 200, 2 ** 300)  # should return 6 but returns 0

Note it is the last two calls of last_digit that cause this warning / wrong return. Also note that if the result of the numbers to the power of each other is 0 then the function should return 1 so ignore lines

if num == 0
   return print 1
end

Upvotes: 1

Views: 331

Answers (1)

steenslag
steenslag

Reputation: 80065

What you are looking for is modular exponentiation. It is supported by ruby, but sort of hidden in the docs; just an extra option of Integer's pow.

def last_digit(n1, n2)
  n1.pow(n2, 10)
end

Upvotes: 8

Related Questions