Solution: Last Digit of Fibonacci Number
Solution for the Last Digit of the Fibonacci Number Problem.
We'll cover the following
Naive solution
To solve this problem, let’s compute and simply output its last digit:
:
if :
return
allocate an array
for from to
return mod 10
Note that Fibonacci numbers grow fast. For example,
Therefore, if we use C++ int 32
or int64_t
types for storing , we’ll quickly hit an integer overflow. If we reach out for arbitrary precision numbers, like Java’s BigInteger
, or Python’s built-in integers, we’ll notice that the loop runs much slower when the iteration number increases.
Stop and think: The last digit of is 6 and the last digit of is 7. What is the last digit of ?
It’s not difficult to see that the last digit of is equal to 3 and is determined completely by the last digits of and . This suggests a way to make our algorithm more practical. Instead of computing and taking its last digit, we take every intermediate step modulo 10.
Take every intermediate step modulo 10
Here is the main message of this programming challenge: when we need to compute the result of a sequence of arithmetic operations modulo , we take the result of every single operation modulo . This way, we ensure that the numbers we’re working with are small (they fit into standard type in our favorite programming language) and that arithmetic operations are performed quickly on them.
:
if :
return
allocate an array
for from to
mod 10
return
Code
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.