我是一個新手,我知道這個我在互聯網上得到的C程序(學分:http://www.geeksforgeeks.org/archives/28)工作正常。
把x提升到n的能力
#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)。非常感謝你!該y/2
用於計算臨時
這是一個遞歸函數 - 谷歌「遞歸」 – Jason
你應該學會調試/斷點/監視/跨過/踏進等調試技術。然後去調試代碼。 –
Alexander Stepanov(C++ STL的設計者)給出了一個以此爲例的系列講座。他解釋了這個問題,並指出這種算法在200BC是古印度數學家所熟知的。看到我的答案的鏈接。 –