What is the fastest way to compute large power of 2 modulo a number

前端 未结 5 2164
南方客
南方客 2020-12-06 02:48

For 1 <= N <= 1000000000, I need to compute 2N mod 1000000007, and it must be really fast!
My current approach i

5条回答
  •  我在风中等你
    2020-12-06 03:33

    It can be solved in O((log n)^2). Try this approach:-

    unsigned long long int fastspcexp(unsigned long long int n)
    {
        if(n==0)
            return 1;
        if(n%2==0)
            return (((fastspcexp(n/2))*(fastspcexp(n/2)))%1000000007);
        else
            return ( ( ((fastspcexp(n/2)) * (fastspcexp(n/2)) * 2) %1000000007 ) ); 
    }
    

    This is a recursive approach and is pretty fast enough to meet the time requirements in most of the programming competitions.

提交回复
热议问题