What does the y/2 do in this function that recursively finds a number raised to a certain power?

Viewed 57

I understand that dividing the power by 2 with each recursive call helps us approach the base case, but could someone explain the intuition behind why dividing the power by 2 in each recursive call works? Thank you!

int power(int x, unsigned int y) 
{ 
    int temp; 
    if( y == 0) 
        return 1; 
    temp = power(x, y/2); 
    if (y%2 == 0) 
        return temp*temp; 
    else
        return x*temp*temp; 
} 

Note: Function sourced from GeeksForGeeks

0 Answers
Related