我是一个新手,我知道我在 Internet 上某个地方获得的这个 C 程序(学分:http ://www.geeksforgeeks.org/archives/28 )可以正常工作。
#include<stdio.h>
float power(float x, int y)
{
float temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
{
if(y > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}
/* Program to test function power */
int main()
{
float x=2;
int y=5;
printf("%f", power(x, y));
getchar();
return 0;
}
我只是想知道如何以及为什么。我在此函数中的代码行之后提出了问题/评论...
float temp;
if( y == 0)
return 1;
//this I understand because for instance 2^0 is 1
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
//if y is even, eg. 2^4 then 2^2 * 2^2 is still equal to 16
else
{
if(y > 0)
//this part I don't get anymore. eg. 2^5, then temp=2^(5/2)
return x*temp*temp;
//2 * 2^(5/2) * 2^(5/2) how? this will become 64 but the answer is 32.
//but when I run the program it halts the right answer ie, 32
else
return (temp*temp)/x;
}
请向我解释发生了什么。也许我只是错过了一些东西。以及它是如何变成O(lg n)运行时间的。非常感谢你!