Advertisement
Guest User

Fibonacci Sequence

a guest
Oct 17th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
J 1.55 KB | None | 0 0
  1. NB. Run as /path/to/jconsole Fib.ijs <n>
  2. NB. Fibonacci in 32 characters by Robert 'Probie' Offner
  3. NB. This is kind of a cop-out, since my chosen language has
  4. NB. primitives for calculating Taylor coefficients.
  5. NB. ".>2{ARGV reads the argument and converts it from a string to a number
  6. NB. i. makes an array from 0 to the argument on the right
  7. NB. The taylor expansion of fibonacci is s(x)=x/(1-x-x*x)
  8. NB. In J this is written as (x % ((1 - x) - *:x))
  9. NB. Because of how order of operations work in J, this is (x % (1 - x) - *:x)
  10. NB. But we can make this shorter, -.x is shorthand for 1-x in J
  11. NB. This gives us (x % -. x - *:x)
  12. NB. J does *not* treat functions as first class objects, so they can't
  13. NB. just be passed around to other functions. This allows for a useful
  14. NB. shorthand where we can just remove the references to x, making (%-.-*:)
  15. NB. an anonymous function which expects one argument (x) and returns
  16. NB. (x % -. x - *:x)
  17. NB. t. is a function which takes a function as an argument and returns a new
  18. NB. function (an adverb in J speak) that gives us the Taylor coefficents,
  19. NB. of the function it was given. Implicit broadcasting applies (%-.-*:)t.
  20. NB. to each element of the array produced by i.
  21. NB. echo&>  prints each element of the array
  22. NB. Finally we require exit to stop J from opening in interactive mode
  23. NB. Final count:
  24. NB. 9  characters to read input
  25. NB. 12 characters to calculate the Fibonacci sequence up to the input
  26. NB. 6  characters to print
  27. NB. 5  characters of pointless overhead from J
  28. exit echo&>(%-.-*:)t.i.".>2{ARGV
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement