FreddieCodes FreddieCodes - 1 year ago 40
Ruby Question

Last digit of a large number (Ruby) how to deal with NaN?

Here's my code:

def last_digit(n1, n2)
array = (n1.to_i ** n2.to_i).to_s.split("")
array[-1].to_i
end


TEST: The last decimal digit of (2^200)^(2^300), which has over 10^92 decimal digits, is 6

I'm trying to return the last digit of a last number and I'm sure this correct but when I run tests 2 return as failing.

I think it's due to the numbers being too large, how do I get this code to remain accurate no matter how large it gets.

And also how do I deal with NaN, I've searched and struggled to find anything useful.

Thanks for your help.

Answer Source

There's an effective algorithm which assumes that only the last digit of a number being powered matters. Please, try it out on your tests and feel free to correct any flaw in this implementation that you'll find by running them

def digit_of_power(digit, n)
  digit = digit % 10

  case digit
  when 0, 1, 5, 6 then digit
  else
    digit_of_square = digit * digit

    if n.even?
      digit_of_power(digit_of_square, n / 2)
    else
      digit * digit_of_power(digit_of_square, (n - 1) / 2) % 10
    end
  end
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download