cubbi.com: fibonacci numbers in j languages: [english] [русский]
J
Date: 1990
Type: Vector language
Usage: statistics, science, and everything else APL does. (J is APL's successor)

ALGORITHM 1A: BINARY RECURSION
NB. f returns n'th Fibonacci number
NB. It uses ALGORITHM 1A - BINARY RECURSION
f =: 1:`($:@<:&<:+$:@<:)@.(1:<])
NB. Output
'35th Fibonacci number is';f 35

ALGORITHM 2A-1: DATA STRUCTURE - INFINITE LIST
NB. l returns the list of n first Fibonacci numbers
NB. This function is based on the example from the J Software "J Dictionary" book.
l =: 1x"0`((],+/@(_2&{.))@$:@<:)@.*
NB. f returns the nth Fibonacci number
NB. It uses ALGORITHM 2A-1 - DATA STRUCTURE - SIMPLE LIST
f =: {:&l
NB. Output
'200th Fibonacci number is';f 200

ALGORITHM 2B: SIMPLE RECURSION
NB. f returns the nth Fibonacci number
NB. It uses ALGORITHM 2B - SIMPLE RECURSION
l =: 0x 1"0`(}.&(],+/)@$:@<:)@.*
f =: {:&l
NB. Output
'200th Fibonacci number is';f 200

ALGORITHM 2C: NON-RECURSIVE LOOP
NB. This program prints out the 200'th Fibonacci number
NB. It uses ALGORITHM 2C - NON-RECURSIVE LOOP
'200th Fibonacci number is';{:}.@(,+/)^:200 (0 1x)

ALGORITHM 3A: MATRIX EQUATION
NB. mm is matrix multiplication
mm =: +/ .*
NB. ms is matrix square
ms =: mm[
NB. mp is matrix power
mp =: 4 : '((x.&mm@ms&$:&<.&-:)"0)`((ms&$:&-:)"0)`(x."0)@.(2&<:-2&|)y.'
NB. f return nth Fibonacci number
NB. It uses ALGORITHM 3A - MATRIX EQUATION
f =: {.&,&((2 2$1 1 1 0x)&mp)
NB. Output
'50,000th Fibonacci number is';f 50000

ALGORITHM 3B: FAST RECURSION
NB. f returns the n'th Fibonacci number
NB. It uses ALGORITHM 3B - FAST RECURSION
l =: (2 1x"0`((((([:*:+)+[:*:[),*+[*+)/&$:&(<:&<.&-:))`(((*+[*+),+&*:)/&$:&(<.&-:&<:))@.(2&|))`(1 1x"0))@.(*@<:@<:)
f =: {.&l
NB. Output
'50,000th Fibonacci number is';f 50000

ALGORITHM 3C: BINET'S FORMULA
NB. phi is the golden section
phi =: -:>:%:5
NB. f returns n'th Fibonacci number
NB. It uses ALGORITHM 3C - BINET'S FORMULA
f =: (%%:5)"0*(phi"0^>:-(-<:phi)"0^>:)
NB. Output
'29th Fibonacci number is';f 29