Reputation:
// i was trying to find (n^n)%1000000007 where n is the nth fibonacci term of the series. example : n=3 ans 4 (2^2)
public class Sol_Big {
public static void main(String args[])
{
int n =10000000;
BigInteger a = BigInteger.ZERO;
BigInteger b = BigInteger.ONE;
BigInteger c = BigInteger.valueOf(1);
BigInteger MOD = BigInteger.valueOf(1000000007);
for (int j=2 ; j<=n ; j++)
{
c = a.add(b);
c=c.mod( MOD);
a = b.mod(MOD);
b = c.mod(MOD);
}
System.out.println(c);
BigInteger result = BigInteger.valueOf(1);
result = c.modPow(c, MOD);
int intval = result.intValue();
System.out.println( intval);
}
}
// my code is working for 10^7 input but for 10^8 and onward it is exceeding time limit....
Upvotes: 0
Views: 244
Reputation: 15173
The trick is to notice that you can calculate the Fibonacci numbers using matrix multiplication:
| 0 1 | | a | | b |
| 1 1 | * | b | = | a + b |
With this knowledge, we can calulate the n-th Fibonacci number:
| 0 1 |^n | 0 |
| 1 1 | * | 1 |
Because matrix multiplication is associative, we can efficiently calculate m^n.
n
is even, m^n = m^(n/2) * m^(n/2)
n
is odd, m^n = m^((n-1)/2)) * m^((n-1)/2)) * m
Note that we need the same thing twice, but we only have to compute it once.
This makes it possible to calculate the n-th Fibonacci number in O(log n)
.
I leave it to you to write the code.
Upvotes: 2