To find n^k,using brute force,
Initialize result to 1.
Iterate from 1 to k and multiply n to result.
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.
Complexity for this code is O(log(k)).
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 );