Re: Recursive Functions
From: Tim Woodall (google_at_woodall.me.uk)
Date: 10/29/03
- Next message: Rick: "Re: Dynamic arrays"
- Previous message: Alex: "Re: Dynamic arrays"
- In reply to: Richard Heathfield: "Re: Recursive Functions"
- Next in thread: James Hu: "Re: Recursive Functions"
- Reply: James Hu: "Re: Recursive Functions"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 29 Oct 2003 05:27:39 -0800
Richard Heathfield <dontmail@address.co.uk.invalid> wrote in message news:<bnmmch$oe8$1@hercules.btinternet.com>...
> Glen Herrmannsfeldt wrote:
>
<snip>
> > However, requiring it as a recursive function does scream of homework. A
> > simple for loop should be easier and faster.
>
> 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?
I'm surprised there is much if any difference:
long mpow(long x, long e)
{
long r=1;
while(e)
{
if(e&1)
r*=x;
x*=x;
e>>=1;
}
return r;
}
Its fairly trivial to remove one multiplication at the cost of n if
tests (where n is the number of bits in e) and one multiplication can
become an assignment but other than that I don't think fewer
multiplications are possible using the square and multiply idiom. IIRC
Knuth goes into this in some detail and mentions some exponents where
this idiom does not use the minimum possible number of
multiplications. (e=15 being the smallest which can be evaluated as
mpow(mpow(x,3),5))
(Getting very OT now. squaring is particularly fast when very big
number are involved where FFT techniques become "efficient")
Tim.
- Next message: Rick: "Re: Dynamic arrays"
- Previous message: Alex: "Re: Dynamic arrays"
- In reply to: Richard Heathfield: "Re: Recursive Functions"
- Next in thread: James Hu: "Re: Recursive Functions"
- Reply: James Hu: "Re: Recursive Functions"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|