Here are a couple approaches:
First, make a list, then take the last thing in it.

   fib_list=:3 : 0
z=.0 1
for. i.y-1 do.
  z=.z,+/_2{. z
end.
if. y>0 do. z else. 0 end.  NB. this only used to make fib_list 0 correct
)

   fib_list 10
0 1 1 2 3 5 8 13 21 34 55

   fib=:{:@fib_list

   fib 10
55

   fib 0
0

Or use matrix multiply

   mp=:+/ . *

   ]W=:*i.2 2
0 1
1 1

W takes one fib pair to the next one
   W mp 13 21
21 34

   fib2=:3 : '{. W&mp^:y 0 1'

   fib2 10
55

   NB. It even works correctly for negative integers

   fib2 _2
_1

----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to