0

I want to calculate 2^N for large value of N i.e. upto 10^9 with mod operation. Used an iterative approach but its taking a lot of time for the input 10^8.

for(long i=1;i<=n;i++){ res=(res*2)%1000000007 }

Its taking time in calculating for n=10^8 and above.

1 Answers1

0

You can increase the speed by squaring as well as multiplying by two - e.g. 2^4 can be reached as 2*2 => 4, 4*4 => 16.

Start with 2. If N is even, square what you have and halve N. If N is odd, multiply by two and decrement N. Apply the modulus as you go.

You may have to be careful the squaring doesn't overflow.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64