pow()实现在cmath和有效的替换

7 c c++ math cmath

我已经阅读了通过执行来cmath计算.当它是整数时,不应该使用它,因为它会大大减慢计算速度.有什么替代方案pow(a,b)exp(b*log(a))b

  1. 用相同的常数计算很多连续的pow()sa
  2. 它是事先知道这b肯定是一个整数?

我正在寻找在这些特定情况下有效的快速替代方案.

Dav*_*ica 8

多年来我收集了许多更快的替代方案,这些方案通常依赖于recursive函数的实现,并且在有保证的情况下进行位移以处理乘法.以下提供适合的功能integer,floatdouble.它们带有正常disclaimer:而快速并非所有可能的测试都已运行且用户应该在调用之前验证输入是否正确并且返回...等等,等等,等等......但是,它们非常有用:

正如蓝月所指出的那样,我认为适当归属于Geeks for Geeks Pow(x,n).我早就失去了链接..看起来像他们.(减去一两个调整).

/* Function to calculate x raised to the power y

    Time Complexity: O(n)
    Space Complexity: O(1)
    Algorithmic Paradigm: Divide and conquer.
*/
int power1 (int x, unsigned int y)
{
    if (y == 0)
        return 1;
    else if ((y % 2) == 0)
        return power1 (x, y / 2) * power1 (x, y / 2);
    else
        return x * power1 (x, y / 2) * power1 (x, y / 2);

}

/* Function to calculate x raised to the power y in O(logn)
    Time Complexity of optimized solution: O(logn)
*/
int power2 (int x, unsigned int y)
{
    int temp;
    if (y == 0)
        return 1;

    temp = power2 (x, y / 2);
    if ((y % 2) == 0)
        return temp * temp;
    else
        return x * temp * temp;
}

/* Extended version of power function that can work
for float x and negative y
*/
float powerf (float x, int y)
{
    float temp;
    if (y == 0)
    return 1;
    temp = powerf (x, y / 2);
    if ((y % 2) == 0) {
        return temp * temp;
    } else {
        if (y > 0)
            return x * temp * temp;
        else
            return (temp * temp) / x;
    }
}

/* Extended version of power function that can work
for double x and negative y
*/
double powerd (double x, int y)
{
    double temp;
    if (y == 0)
    return 1;
    temp = powerd (x, y / 2);
    if ((y % 2) == 0) {
        return temp * temp;
    } else {
        if (y > 0)
            return x * temp * temp;
        else
            return (temp * temp) / x;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果[这是你收集的地方](http://www.geeksforgeeks.org/write-ac-program-to-calculate-powxn/),请归因于此. (5认同)
  • @BlueMoon感谢您的链接.这看起来就像他们最初来自哪里.在我的盒子里,他们住在`〜/ dev/src -c/function/math/fn-power.c`,原来的链接已经丢失了.我添加了归因. (3认同)