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;
}

Sreekumar Kj
Sreekumar (KJ) has been a hobby programmer from school days. Codemarvels is his personal blog from the year 2010, where he writes about technology, philosophy, society and a bit about physics. He now runs a conversational AI company - DheeYantra - focusing his efforts to help businesses improve operational efficiency using digital employees powered by AI.