我已经阅读了通过执行来cmath计算.当它是整数时,不应该使用它,因为它会大大减慢计算速度.有什么替代方案pow(a,b)exp(b*log(a))b
pow()sab将肯定是一个整数?我正在寻找在这些特定情况下有效的快速替代方案.
多年来我收集了许多更快的替代方案,这些方案通常依赖于recursive函数的实现,并且在有保证的情况下进行位移以处理乘法.以下提供适合的功能integer,float和double.它们带有正常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)
| 归档时间: |
|
| 查看次数: |
13023 次 |
| 最近记录: |