So I have a homework to make a flowchart of an algorithm printing first N terms of Fibonacci sequence. It’s not hard, sure, but the teacher told us this could be done in as little as six flowchart “balloons”. And here is the problem – I wanted to do it this way but I just don’t seem to be able to… Namely, I think the shortest way is to check if N>2 – if not, we have to check if it’s 1 or 2 and print 0 or 1 respectively. Only after that can we use the “regular” F(n)=F(n-1)+F(n-2) formula – otherwise, it would crash. Writing more formally:
- input N
- N>2?
- No: check if it’s 1. If so, print 0 and stop.
- No: check if it’s 2. If so, print 0 and 1 and stop.
- Yes: proceed to 3
- Let i=3. While i < N: fib(i)=fib(i-1)+fib(i-2) and print fib(i).
- Stop.
The problem is, I suppose it would take something around 10 boxes to make this, if not more. What could be the shorter way, then? All the algorithms I find online tend to presume we would get only N more than 2 which may not be the case. Could you please help?
EDIT: OK, I tweaked it to 8 boxes and think it’s as little as one can go. Something like this:
- Input N
- Let older=0, younger=1 (respectively: the (n-2)th and (n-1)th term of the series), current=1, i=2.
- Is N<=1?
- Yes: output older, end.
- No: proceed to 4
- Output older, younger.
- i < N?
- Yes: current = older+younger, older = younger, younger = current, i+=1. Print current, go to 5.
- No: end.
Could something be tweaked further here?
If “Stop” needs to be its own step, that would make step 6.