C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Variable: A temporary variable "temp" is used to store the previous value for later use.
Range: We use range() to loop over the entire numeric range to the desired Fibonacci number.
RangeNote: We do not need recursion for a Fibonacci sequence. Iteration, with a temporary variable, works as well—and is likely faster.
Python program that computes Fibonacci sequence
def fibonacci(n):
a = 0
b = 1
for i in range(0, n):
temp = a
a = b
b = temp + b
return a
# Display the first 15 Fibonacci numbers.
for c in range(0, 15):
print(fibonacci(c))
Output
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
Tip: Using lookup tables or "memoizing" math computations is usually faster for nontrivial requirements.
MemoizeList: To access small Fibonacci numbers quickly, store them in a list and just reuse that list when required.
ListPython program that displays Fibonacci sequence
def fibonacci2(n):
a = 0
b = 1
for i in range(0, n):
# Display the current Fibonacci number.
print(a)
temp = a
a = b
b = temp + b
return a
# Directly display the numbers.
fibonacci2(15)
Output
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
Zero: Fibonacci himself did not include the 0, but modern scientists do. It is best to side with modernity.
Tip: I recommend checking as many sources as possible when researching. This includes websites other than this one.
But: Don't spend the whole day browsing Wikipedia if you are doing something important.
Quote: Fibonacci began the sequence not with 0, 1, 1, 2, as modern mathematicians do but with 1, 1, 2.
Fibonacci: Wikipedia