Fibonacci
Understanding the Fibonacci Series
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. It typically starts with:
0, 1, 1, 2, 3, 5, 8, 13, ...
The Basic Recursive Approach
The classic recursive method for calculating Fibonacci numbers is:
FUNCTION Fibonacci(n):
IF n <= 1 THEN
RETURN n
END IF
RETURN Fibonacci(n-1) + Fibonacci(n-2)
This approach results in two recursive calls for each number, making it inefficient for larger numbers.
Introducing the LinearFibonacci Algorithm
The LinearFibonacci method offers an optimization by returning two consecutive Fibonacci numbers during each recursive call.
Algorithm:
Input: A non-negative integer k.
Output: A pair of consecutive Fibonacci numbers (Fib(k), Fib(k-1)).
FUNCTION LinearFibonacci(k):
IF k <= 1 THEN
RETURN (k, 0)
END IF
(i, j) = LinearFibonacci(k-1)
RETURN (i+j, i)
This method reduces the overall recursive calls by returning two values at once.
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.