In rashida.par's Recursive function to find X to the power n (http://www.go4expert.com/showthread.php?t=9307) I see that she intelligently used recursion to find the power of x to n. So, I was wondering whether we can do this iteratively also, I always do that - trying to find a iterative solution to a recursive one.

Being more of a Perl programmer than C, I wrote my code in Perl - can be understood by any programmer. I also benchmarked the recursive function to the iterative version.

As we see here, the iterative version performs much better than the recursive one, the reason being the recursive version need more memory for function call stacks etc.

I hope this was helpful to you all.

rai_gandalf

8Apr2008 00:18

Re: Iterative Function To Find X to the power N

As was evident from the Recursive implementation, there was tail recursion, which is both redundant & inefficient. Tail recursion must always be replaced with a more efficient, easier to comprehend iterative counter-part, as you have done here.

Only, you have done it in Perl - a language which I do not know much about - so I got to learn the basics of a new language as well!