ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Fibonacci Sequence Iteratively

Python

Goal -- WPM

Ready
Exercise Algorithm Area
1def fibonacci_iterative(n):
2"""Generates the first n Fibonacci numbers iteratively.
3
4Args:
5n: The number of Fibonacci numbers to generate.
6
7Returns:
8A list containing the first n Fibonacci numbers.
9"""
10if not isinstance(n, int) or n < 0:
11raise ValueError("Input must be a non-negative integer.")
12
13if n == 0:
14return []
15elif n == 1:
16return [0]
17
18fib_sequence = [0, 1]
19a, b = 0, 1
20
21# We already have the first two numbers, so loop n-2 times
22for _ in range(n - 2):
23next_fib = a + b
24fib_sequence.append(next_fib)
25a = b
26b = next_fib
27
28return fib_sequence
Algorithm description viewbox

Fibonacci Sequence Iteratively

Algorithm description:

This function generates a list containing the first `n` numbers of the Fibonacci sequence using an iterative approach. The Fibonacci sequence is a series where each number is the sum of the two preceding ones, usually starting with 0 and 1. It appears in many areas of mathematics and nature, such as in the branching of trees and the arrangement of leaves.

Algorithm explanation:

The iterative Fibonacci generator maintains the last two numbers in the sequence to compute the next one. It initializes a list with the first two Fibonacci numbers (0 and 1). Then, it iterates `n-2` times. In each iteration, it calculates the next Fibonacci number by summing the previous two, appends it to the list, and updates the two preceding numbers. This avoids the redundant calculations inherent in a naive recursive approach. The time complexity is O(n) because it performs a constant amount of work for each of the `n` numbers. The space complexity is O(n) to store the resulting list of Fibonacci numbers. Edge cases for `n=0` and `n=1` are handled explicitly.

Pseudocode:

1. Define a function `fibonacci_iterative(n)`.
2. Validate that `n` is a non-negative integer; raise an error otherwise.
3. If `n` is 0, return an empty list.
4. If `n` is 1, return a list containing only 0.
5. Initialize `fib_sequence` with [0, 1].
6. Initialize `a = 0` and `b = 1`.
7. Loop `n - 2` times:
   a. Calculate `next_fib = a + b`.
   b. Append `next_fib` to `fib_sequence`.
   c. Update `a = b`.
   d. Update `b = next_fib`.
8. Return `fib_sequence`.