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)
- Check if sum of Fibonacci elements in an Array is a Fibonacci number or not
- Find the sum of power of bit count raised to the power B
- Compute power of power k times % m
- Find power of power under mod of a prime
- Check if given number is a power of d where d is a power of 2
- Check if a M-th fibonacci number divides N-th fibonacci number
- Larger of a^b or b^a (a raised to power b or b raised to power a)
- Fibonacci modulo p
- Fibonacci Word
- Fibonacci problem (Value of Fib(N)*Fib(N) - Fib(N-1) * Fib(N+1))
- Nth Even Fibonacci Number
- Non Fibonacci Numbers
- GCD and Fibonacci Numbers
- Even Fibonacci Numbers Sum
- Nth XOR Fibonacci number
- K- Fibonacci series
- Fibonacci Search
- Fibonacci Coding
- Sum of Fibonacci Numbers
- Power Set
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.