Generate the Fibonacci sequence in the fewest amount of characters possible. Any language is OK, except for one that you define with one operator, f
, which prints the Fibonacci numbers.
Starting point: 25 14 characters in Haskell:
f=0:1:zipWith(+)f(tail f)
f=0:scanl(+)1f
For the record:
function f(n)if n<2 then return n else return f(n-1)+f(n-2)end end
function f(n){return n<2?n:f(n-1)+f(n-2)}
int f(int n){return n<2?n:f(n-1)+f(n-2);}
I am not much adept of super concise languages... :-P
Chris is right, I just took the simple, recursive algorithm. Actually, the linear one is even shorter in Lua (thanks to multiple assignment)! JavaScript isn't so lucky and Java is worse, having to declare vars...
function f(n)a=1;b=0;for i=1,n do a,b=b,a+b end return b end
function f(n){a=1;b=i=0;for(;i++<n;){x=a+b;a=b;b=x}return b}
int f(int n){int a=1,b=0,i=0;for(;i++<n;){int x=a+b;a=b;b=x;}return b;}
I would write Lua's code with
local a,b=1,0
but it is longer, so let's pollute _G! ;-) Idem for JS.For completeness, here are the terminal recursive versions. Lua's one, using tail call, is as fast as the linear one (but 69 chars, it is the longest!) - need to call them with three params, n,1,0.
function f(n,a,b)if n<1 then return b else return f(n-1,b,a+b)end end
function f(n,a,b){return n<1?b:f(n-1,b,a+b)}
int f(int n,int a,int b){return n<1?b:f(n-1,b,a+b);}
Delphi Prism (Delphi for .net)
49 chars
22 characters with dc:
Invoke with either:
Or:
Note: not my work, poached from perlmonks.
x86 (C-callable) realmode, 14 bytes.
Input is n on stack, returns Fn in AX.
Windows XP (and later versions) batch script. This batch function when given a single argument - amount, generates amount+1 Fibonacci numbers and returns them as a string (BATCH doesn't really have sets) in variable %r% (369 characters, or 347 characters - if we remove indentation):
And here's the complete script, to see it in action (just copy-past it into a CMD or BAT file and run it):
MS Excel: 11 characters:
Type
1
in the top 2 cells, then put the above formula in cell A3. Copy the formula down the spreadsheet.Starts losing accuracy due to floating point rounding on row 74.
Exceeds 10^307 and overflows to a
#NUM!
error on row 1477.