![]() |
Iterative Function To Find X to the power N
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. The Iterative SolutionCode: Perl
Test run of the code: Code: Perl
Code:
[pradeep@go4expert perl_test]$ perl power_iterative.plBenchmarkingI also benchmarked the recursive function to the iterative version to see which one performs better. Code: Perl
Result: Code:
[pradeep@go4expert perl_test]$ perl power_iterative.plI hope this was helpful to you all. |
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! Regards, Rajiv |
| All times are GMT +5.5. The time now is 07:43. |