The fastest way to calculate (n + 1) ^ j from (n ^ j)

I need to calculate 0 ^ j, 1 ^ j, ..., k ^ j for some very large k and j (both orders of several millions). I use GMP to handle large integers (yes, I need integers as I need full precision). Now, I wonder when I try to calculate n ^ j, is there no way to speed up the calculation of (n + 1) ^ j instead of starting from scratch?

Here is the algorithm I'm using now to calculate power:

mpz_class pow(unsigned long int b, unsigned long int e)
{
    mpz_class res = 1;
    mpz_class m = b;

    while(e)
    {
        if(e & 1)
        {
            res *= m;   
        }

        e >>= 1;
        m *= m;
    }

    return res;
}

As you can see, every time I start from scratch and it takes a lot of time.

+4
source share
2 answers

n^j, n, k n^j = k^j * (n/k)^j? n^j k^j, (n/k)^j.

O(sqrt(n)) n. n^j O(log(j)) Squaring, .

, , , :

  • n log(j), n^j .

  • , n^j , {(2*n)^j, (3*n)^j, ..., ((n-1)*n)^j, n * n^j} .

  • n , log(j), , , , , , .

  • n 2 ( const), j th , .

  • n ( ), .

. , . , , ( 3, 7 ..)

+1

(n + 1) ^ j n ^ j + jn ^ (j-1) + j (j-1)/2 * n ^ (j-2) +... + 1 memoize , (n + 1) ^ j O (n) . j, j * (j-1)/2,... , , O (n).

+1

Source: https://habr.com/ru/post/1668089/


All Articles