For the record:
- Lua (66 chars):
function f(n)if n<2 then return n else return f(n-1)+f(n-2)end end
- JavaScript (41 chars):
function f(n){return n<2?n:f(n-1)+f(n-2)}
- Java (41 chars):
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...
- Lua (60 chars):
function f(n)a=1;b=0;for i=1,n do a,b=b,a+b end return b end
- JavaScript (60 chars):
function f(n){a=1;b=i=0;for(;i++<n;){x=a+b;a=b;b=x}return b}
- Java (71 chars):
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.
- Lua (69 char, longer!):
function f(n,a,b)if n<1 then return b else return f(n-1,b,a+b)end end
- JavaScript (44 chars):
function f(n,a,b){return n<1?b:f(n-1,b,a+b)}
- Java (52 chars):
int f(int n,int a,int b){return n<1?b:f(n-1,b,a+b);}