On Sat, Mar 6, 2010 at 9:36 PM, Dennis Ruffer <[email protected]> wrote:
>> -----Original Message-----
>> From: [email protected] [mailto:gforth-
>> [email protected]] On Behalf Of Terrence Brannon
>> But I would like to know why mine does not work:

> Remember that n is left on the stack after the last ENDOF, so you end up
> putting it on again.

I removed one reference to n, but I get a Stack underflow:


: fib { n -- fibn }
  assert( n 0>= )
  n CASE
    0 OF 0 ENDOF
    1 OF 1 ENDOF
    2 OF 1 ENDOF        
    ( otherwise ) 1 - recurse n 2 - recurse +
  ENDCASE ;


>
> Not sure why you want 2 recurse's either or the other n 2 -.

Because the nth Fibonacci number is the sum of the prior two Fibonacci numbers:

F(n) = F(n-1) + F(n-2)

So naively, you simply (and redundantly and with no memoization)
calculate F(n-1) and add that to F(n-2)

>
> I can't follow the logic, but then the people in that shootout are much
> better at it than I am. ;)

I was actually trying a Counted loops exercise -
http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Counted-loops-Tutorial.html


Reply via email to