11
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)
1I realize this is quite an old challenge at this point, but note that you've accepted an answer which is not the shortest. Since this is a code golf competition, the shortest answer should be the one that's marked accepted. – Alex A. – 2016-02-12T00:21:08.290
1I think this is too similar to the linked question. Most solutions there can easily be modified to handle the first-n case. – hammar – 2012-01-17T20:52:11.530
In the case of Python, the interesting thing is that I need four lines of code, and two levels of indentation in my sample. I suspect there is a one liner in python, but I can't find it. – Warren P – 2012-01-17T20:56:26.500
I believe that the questions of "How does it start?" has a lot of history behind it, but I was usually taught starting with 1, 1. Does the Wikipedia give an authoritative source for 0, 1? – dmckee --- ex-moderator kitten – 2012-01-17T21:02:10.237
I remember it being introduced as
1, 1, ..
in grade 7 when I was told about it. – Warren P – 2012-01-17T21:04:46.5333Everywhere I've seen, the base cases are defined as
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). – hammar – 2012-01-17T21:19:49.5371And defining
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}]]
. – Peter Taylor – 2012-01-17T23:36:53.6031@Peter: Now that a good reason to prefer one to the other (I'd long preferred 0, 1 on esthetic grounds, but don't believe those to be pressing in and of themselves). – dmckee --- ex-moderator kitten – 2012-01-18T03:33:05.763