Given a number n. You are required to find ( Fib(n) ^ Fib(n) ) % 10^9 + 7, where Fib(n) is the nth fibonacci number.
Input : n = 4
Output : 27
4th fibonacci number is 3
[ fib(4) ^ fib(4) ] % 10^9 + 7 = ( 3 ^ 3 ) % 10^9 + 7 = 27
Input : n = 3
Output : 4
3th fibonacci number is 2
[ fib(3) ^ fib(3) ] % 10^9 + 7 = ( 2 ^ 2 ) % 10^9 + 7 = 4
If n is large, fib(n) will be huge and fib(n) ^ fib(n) is not only difficult to calculate but its storage is impossible.
( a ^ (p-1) ) % p = 1 where p is prime number (using Fermat Little Theorem).
( a ^ a ) % m can be written as ( ( a % m ) ^ a ) % m
It is also possible to write any number ‘a’ as a = k * ( m – 1 ) + r (Using Division Algorithm)
where ‘k’ is quotient and ‘r’ is remainder. We can say that r = a % (m-1)
So, Steps to reduce our calculation, lets suppose a = fib(n)
( a ^ a ) % m = ( ( a % m ) ^ a ) % m = ( ( a % m ) ^ ( k * ( m - 1 ) + r ) ) % m = ( ( ( a % m ) ^ ( m-1 ) ) ^ k * ( a % m ) ^ r ) % m = ( (1 ^ k) * ( a % m ) ^ r ) % m = ( ( a % m ) ^ r ) % m = ( ( a % m ) ^ (a % (m-1) ) % m
Below is the implementation of above approach :
Time Complexity: log(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.