Re: Recursive Functions
From: Eric Sosman (Eric.Sosman_at_sun.com)
Date: 10/29/03
- Next message: Mike Wahler: "Re: arrow operator"
- Previous message: Glen Herrmannsfeldt: "Re: [OT] Re: Recursive Functions"
- In reply to: Richard Heathfield: "Re: Recursive Functions"
- Next in thread: Micah Cowan: "Re: Recursive Functions"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 29 Oct 2003 10:29:15 -0500
Richard Heathfield wrote:
>
> Hmmm. I raised 7 to the power 7777 using recursion and iteration. (Since the
> result occupies over 6500 decimal digits, I won't display it here!)
>
> The recursive calculation took 0.22 seconds, and the iterative version 1.06
> seconds - almost five times slower. Perhaps you could demonstrate an
> iterative version that can hold a candle to the recursive technique?
SomeType my_power(SomeType x, unsigned int n) {
/* This is the right-to-left binary method used
* by the O.P., expressed iteratively rather
* than recursively. A similar left-to-right
* method would use one less multiplication
* (note that the first multiplication in this
* method is always by unity, and thus wasted),
* but needs extra code to find the high-order
* 1-bit of `n'. Other methods are faster for
* certain values of `n' (e.g., 15), but are
* also more complicated. See Knuth, "The
* Art of Computer Programming, Volume II:
* Seminumerical Algorithms" Section 4.6.3;
* this is Algorithm A from that section.
*/
SomeType y = 1;
/* Optional: Make an explicit test for x==0 here.
* As things stand, my_power(0,0) -> 1.
*/
for (;;) {
if (n & 1)
y *= x;
if ((n >>= 1) == 0)
return y;
x *= x;
}
}
-- Eric.Sosman@sun.com
- Next message: Mike Wahler: "Re: arrow operator"
- Previous message: Glen Herrmannsfeldt: "Re: [OT] Re: Recursive Functions"
- In reply to: Richard Heathfield: "Re: Recursive Functions"
- Next in thread: Micah Cowan: "Re: Recursive Functions"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|