[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: To understand recursion, one must first understand recursion (was Re: apple iie overheat question)
- Subject: Re: To understand recursion, one must first understand recursion (was Re: apple iie overheat question)
- From: "Hidehiko Ogata" <hog@aqu.candybar.ne.jp>
- Date: Sat, 7 May 2005 17:59:31 +0000 (UTC)
- Newsgroups: comp.sys.apple2
- Organization: Bekkoame Internet Inc.
- References: <3yNee.7639$BE3.859@newsread2.news.pas.earthlink.net> <cvPee.38$r04.117@news.oracle.com> <xTPee.11819$tQ.9886@fed1read06> <m3wtqcgifm.fsf@pearl.local>
- Xref: g2news1.google.com comp.sys.apple2:10816
Scott Hemphill wrote:
> You could still use recursion, but tame it a little bit by not recalculating
> a value that has already been calculated:
>
> #define MAXTABLE 2000 // or whatever
> double F(int n)
> {
> static double fibtable[MAXTABLE] = {0, 1};
> static int maxfib = 1;
> if (n < 0 || n >= MAXTABLE) return 0; // catch error
> if (n > maxfib) {
> fibtable[n] = F(n-1) + F(n-2);
> maxfib = n;
> }
> return fibtable[n];
> }
Hmm, shouldn't today's compilers be smart enough to detect and
optimize tail-recursion? As in:
double fib(int n)
{
return fib_iter(1, 0, n);
}
double fib_iter(double old, double older, int count)
{
return count ? fib_iter(old + older, old, --count) : older;
}
(Excuse me for butting in... it's an irresistible subject for
a scheme fan ;)
--
// }{idehiko ()gata "I hope I didn't hurt you too much
\X/ Amiga since '86 when I killed you..." - Elmer Fudd
bekkoame is a classic Japanese candybar.