Fibonacci numbers in J
Example for versions
j602
This example uses Binet’s formula.
g =: -: >: %:5
is equivalent to g =: 0.5 * (1 + 5 ^ 0.5)
and assigns name g
to value of golden ratio. %:
extracts square root of the number, >:
increments the number, -:
divides the number by two. Operations are done from right to left, unless there are no parenthesis in the formula.
fibb=: (%:5) %~ g&^ -- (1-g)&^
is equivalent to fibb =: (0.2 ^ 0.5) * (g &^ -- (1-g) &^)
; this defines a formula for F(n) given the value of n. %~
is division, with dividend and divisor swapped.
i.16
generates numbers from 0 to 15, inclusive.
load 'printf'
g=: -: >: %:5
fibb=: (%:5) %~ g&^ - (1-g)&^
fstr=: '...' ,~ ,~^:4 '%d, '
fstr printf fibb 1+i.16
Comments
]]>blog comments powered by Disqus
]]>