DEV Community

loading...

Discussion on: Daily Challenge #250 - Last Digit of a Large Number

Collapse
daviducolo profile image
Davide Santangelo • Edited

ruby

def last_digit(a, b)
  (a**b).digits.first
end 

or

def last_digit(a, b)
  (a**b).to_s[-1].to_i
end 
Collapse
citizen428 profile image
Michael Kohl

digits.first should probably be digits.last, right?

This won't work for big numbers btw, the last example will raise an exception:

last_digit(2**200, 2**300)
(irb):2: warning: in a**b, b may be too big
Traceback (most recent call last):
...
NoMethodError (undefined method `digits' for Infinity:Float)
Collapse
daviducolo profile image
Davide Santangelo

no digits in ruby

12345.digits #=> [5, 4, 3, 2, 1]

so digits.first is correct

Thread Thread
citizen428 profile image
Michael Kohl

Ah yes, somehow I was thinking this would have the same order as chars.to_a, but it doesn't, so you can easily get back the number:

[5, 4, 3, 2, 1].each.with_index.reduce(0) do |result, (n, i)| 
  result + n * 10 ** i
end
#=> 12345
Collapse
wrightdotclick profile image
Thomas Wright

I think this Ruby solution underestimates the complexity required with huge numbers, although the .digits.first is clever! Using a mod 10 solution, like some of the solutions above, would greatly reduce the time/space complexity. brilliant.org/wiki/finding-the-las...