There is a well known question here that asks for a short (least characters) fibonacci sequence generator.
I would like to know if someone can generate the first N elements only, of the fibonacci sequence, in very short space. I am trying to do it in python, but I'm interested in any short answer, in any language. Function F(N) generates the first N elements of the sequence, either returns them as the return of the function or prints them.
Interestingly it seems that the code-golf answers start with 1 1 2
, instead of 0 1 1 2
. Is that a convention in code-golf or programming-in-general? (Wikipedia says the fibonacci sequence starts with zero.).
Python Sample (First 5 Elements):
def f(i,j,n):
if n>0:
print i;
f(j,i+j,n-1)
f(1,1,5)
F_0 = 0, F_1 = 1
or equivalentlyF_1 = 1, F_2 = 1
. The difference is whether you want to start the sequence at index 0 (more common in programming) or 1 (more common in math). \$\endgroup\$F_0 = 0, F_1 = 1
has a definite benefit in simplicity with the matrix representation[[1 1][1 0]]^n = [[F_{n+1} F_n][F_n F_{n-1}]]
. \$\endgroup\$