First-n Fibonacci sequence elements
C
Didn't bother counting, but here's a fun example:
f(n){return n<4?1:f(--n)+f(--n);}
main(a,b){for(scanf("%d",&b);a++<=b;printf("%d ",f(a)));}
Proof it works.
I'm quite proud of this: I got bored, so I rearranged my code (with a few small additions) to make it where each line represents a value in the Fibonacci sequence.
# // 1
f // 1
// // 2
(n) // 3
{/**/ // 5
return n // 8
<2 ? 1:f(--n) // 13
+f(--n); } main(a, b) // 21
{a = 0, b = 0;scanf("%d",&b); for( // 34
;a < b; a+=1) { int res = f(a); printf("%d ", res); } } // 55
Proof it works.
Haskell (26)
Surprisingly, this is only one character longer than the J solution.
f=(`take`s) s=0:scanl(+)1s
I shave off a few characters by:
- Using
take
as a binary operator; - Using
scanl
instead of the verbosezipWith
.
Here's a one-liner Python. It uses floating-point, so there may be some n
for which it is no longer accurate.
F=lambda n:' '.join('%d'%(((1+5**.5)/2)**i/5**.5+.5)for i in range(n))
F(n)
returns a string containing the first n
Fibonacci numbers separated by spaces.