Best Code to find n to the power k(n^k)

To find n^k,using brute force,

ALGORITHM-
Initialize result to 1.
Iterate from 1 to k and multiply n to result.
Return result.

CODE-

result=1;
for(i=1;i<=k;i++)
{
result=result*n;
}

Complexity for this code is O(k).

Its not only about coding for a given task but also making the code efficient in terms of space as well as time.The above code will take a lot of time for computation for larger values of k.

Efficient code–

Complexity for this code is O(log(k)).

ALGORITHM-

power (n,k)
{

if (k==0)
return 1;

if (k is even)
return (power(n,k/2) * power (n,k/2) );

else if (k is odd)
return (power (n,k/2) * power (n,k/2) * n );

}

CODE-

result=1;
while(k)
{
if(k%2!=0){result=result*n;}
n=n*n;
k=k/2;
}

Leave a Comment

Your email address will not be published. Required fields are marked *