Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci sequence calculator seems correct but can't find similar code online. Is there something wrong?

I made a simple Fibonacci sequence calculator for the first 22 terms:

i=1
n=0
while i<=20000:
    i = i + n
    n = i - n
    print(i)

Looks like the result is correct

1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657

but I can't seem to find similar code anywhere online. I think that's a big red flag. Can someone tell me what is wrong here? Is this inefficient code?

like image 609
fibonaccipistacci Avatar asked May 09 '19 00:05

fibonaccipistacci


2 Answers

No, that code is fine. The probable reason you can't find similar code online is that it's unusual to use the subtraction operator in Fibonacci, which is a purely additive function, tn = tn-2 + tn-1.

It works, of course, since addition/subtraction is both commutative and associative, meaning that order and grouping of terms is unimportant:

i = i + n  # iNew = iOld + nOld

n = i - n  # nNew = (iNew)        - nOld
           #      = (iOld + nOld) - nOld
           #      = iOld + (nOld  - nOld)
           #      = iOld + (0)
           #      = iOld

Use of subtraction allows you to bypass needing a third variable, which would be something like this in a lesser language than Python:

nextN = i + n
i = n
n = nextN

In Python, you don't actually need that since you can use tuple assignment such as:

(n, i) = (i, n + i)

With that, everything on the right of the = is evaluated before any assignments to the left.

like image 141
paxdiablo Avatar answered Oct 22 '22 09:10

paxdiablo


It's an unusual way to do it, but it's correct. Your lines:

i = i + n
n = i - n

are the same as doing:

new_i = i + n
n = i
i = new_i

or,

i, n = i + n, i

which would be the usual way in Python.

like image 34
Ned Batchelder Avatar answered Oct 22 '22 08:10

Ned Batchelder