I'm a newbie and I know that this C program which I got somewhere on the Internet (credits: http://www.geeksforgeeks.org/archives/28) works properly.
#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;
}
I'm just wondering how and why. I made my questions/remarks a comment after the line of my the code in this function...
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;
}
Kindly explain to me what happened. Maybe I just missed something. And also how it became a O(lg n) running time. Thank you very much!