Fast Power function in this code is not working when a number is raised to an odd power. What is the problem with this code?
Fast power function
if(b%2==0)
return fastPower(a*a, b/2);
else if(b%2!=0)
return a*fastPower(a*a, b-1/2);
these statements are wrong
understand this
a^b = (a^b/2 * a^b/2); if a is even
a^b = a*(a^(b-1) if b is odd
so correct recursive call are
//Recursive Case
if(b%2==0)
{
int ans= fastPower(a, b/2);
return ans*ans;
}
else return a*fastPower(a, b-1);
i hope this help
if you have more doubts regarding this feel free to ask
if your doubt is resolved mark it as resolved from your doubt section inside your course