Write a function that efficiently calculates the last digits of Fibonacci terms.
fibonacci(4, 2) ➞ 3 fibonacci(524288, 15) ➞ 122520212016581 fibonacci(524289, 18) ➞ 459462970016204514
The input will not be limited to powers of two.