找到你要的答案

Q:Pow function calculation by dynamic programming

Q:利用动态规划pow函数计算

I know that pow(base, power) is a built-in function in C with complexity O(power). Can I reduce the complexity of it by dynamic programming?

我知道战俘(基地、电力)是一个内置的函数在C的复杂度为O(功率)。我可以减少它的复杂性,通过动态规划?

answer1: 回答1:

You can calculate it in O(logn)

int power(int x, unsigned int y)
{
    int temp;
    if( y == 0)
        return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
        return temp*temp;
    else
        return x*temp*temp;
}

Details in Here

你可以在O(logn)的计算

int power(int x, unsigned int y)
{
    int temp;
    if( y == 0)
        return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
        return temp*temp;
    else
        return x*temp*temp;
}

细节在这里

answer2: 回答2:

If your input arguments are non-negative integers, then you can implement your own pow.

Iteratively, with running time = O(n):

unsigned long long pow(unsigned long long x,unsigned int n)
{
    unsigned long long res = 1;
    while (n--)
        res *= x;
    return res;
}

Recursively, with running time = O(n):

unsigned long long pow(unsigned long long x,unsigned int n)
{
    if (n == 0)
        return 1;
    if (n == 1)
        return x;
    return pow(x,n/2)*pow(x,n-n/2);
}

Efficiently, with running time = O(log(n)):

unsigned long long pow(unsigned long long x,unsigned int n)
{
    unsigned long long res = 1;
    while (n > 0)
    {
        if (n & 1)
            res *= x;
        n >>= 1;
        x *= x;
    }
    return res;
}

如果你的输入参数都是非负整数,那么你可以实现自己的战俘。

迭代,运行时间= O(n):

unsigned long long pow(unsigned long long x,unsigned int n)
{
    unsigned long long res = 1;
    while (n--)
        res *= x;
    return res;
}

递归的,运行时= O(n):

unsigned long long pow(unsigned long long x,unsigned int n)
{
    if (n == 0)
        return 1;
    if (n == 1)
        return x;
    return pow(x,n/2)*pow(x,n-n/2);
}

有效,运行时间= O(log(n)):

unsigned long long pow(unsigned long long x,unsigned int n)
{
    unsigned long long res = 1;
    while (n > 0)
    {
        if (n & 1)
            res *= x;
        n >>= 1;
        x *= x;
    }
    return res;
}
c++  dynamic-programming