-3

in this equation

#define mod 1000000007
int n;
int num = ((1<<n)%mod)+2;

I have to left shift 1 by any value of n and then perform mod operation to contain the result within the range of int. But the 1<<n is not showing correct value for bigger values of n such as 1000 or 10000. How to do it ?

Paul R
  • 208,748
  • 37
  • 389
  • 560
Tushar Anand
  • 37
  • 10
  • It does not give correct output because after 31 shifts overflow happens – Ashwani Oct 08 '14 at 12:06
  • 1
    Related (possibly even a duplicate): http://stackoverflow.com/questions/11289495/what-is-the-fastest-way-to-compute-large-power-of-2-modulo-a-number – Paul R Oct 08 '14 at 12:08

1 Answers1

2

The maximum you can left-shift 1 by is CHAR_BIT * sizeof(int) - 2. Any larger amount causes undefined behaviour.

If you want to work with numbers like 210000 you are going to have to use a big integer library (or write your own) , there are no built-in data types that can handle that sort of number accurately.

Another option is to use a smarter algorithm for modular exponentiation.

M.M
  • 138,810
  • 21
  • 208
  • 365