Introduction
The Fibonacci series is a sequence where each number is the sum of the previous two numbers. It is widely used in mathematics, computer science, and nature. The first two terms are 0 and 1, and the series continues indefinitely.
For n = 200, the Fibonacci series is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2)
Where:
Each subsequent number is the sum of the previous two.
sum = 0
, a = 0
, b = 1
sum < n
:sum = a + b
sum
a = b
, b = sum
This method uses loops for better performance (O(n) complexity).
def fibonacci_iterative(n):
a, b = 0, 1
print(a, b, end=" ")
while True:
next_term = a + b
if next_term > n:
break
print(next_term, end=" ")
a, b = b, next_term
# Example usage
n = int(input("Enter the limit: "))
fibonacci_iterative(n)
✔ Optimized for large numbers
✔ Uses iteration (looping)
This method uses recursion, but has O(2ⁿ) complexity, making it slow for large n.
def fibonacci_recursive(n, a=0, b=1):
if a > n:
return
print(a, end=" ")
fibonacci_recursive(n, b, a + b)
# Example usage
n = int(input("Enter the limit: "))
fibonacci_recursive(n)
✔ Simple and elegant
❌ Not optimized for large numbers
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int a = 0, b = 1, sum = 0, n;
// Convert argument to integer
n = atoi(argv[1]);
printf("%d %d ", a, b);
while (sum <= n) {
sum = a + b;
if (sum > n) break;
printf("%d ", sum);
a = b;
b = sum;
}
return 0;
}
✔ Command-line argument support
✔ Faster than recursion
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main(int argc, char *argv[]) {
int n = atoi(argv[1]), sum = 0, i = 0;
while (fibonacci(i) <= n) {
printf("%d ", fibonacci(i));
i++;
}
return 0;
}
❌ Exponential time complexity (O(2ⁿ))
❌ Not suitable for large values of n
This approach stores previously computed values to improve performance.
def fibonacci_memo(n, memo={0: 0, 1: 1}):
if n in memo:
return memo[n]
memo[n] = fibonacci_memo(n - 1, memo) + fibonacci_memo(n - 2, memo)
return memo[n]
def fibonacci_upto_n(n):
i = 0
while True:
fib = fibonacci_memo(i)
if fib > n:
break
print(fib, end=" ")
i += 1
# Example usage
n = int(input("Enter the limit: "))
fibonacci_upto_n(n)
✔ Fast for large inputs
✔ Avoids redundant calculations
Method | Time Complexity | Space Complexity | Best For |
---|---|---|---|
Iterative | O(n) | O(1) | Large numbers |
Recursive | O(2ⁿ) | O(n) | Small numbers |
Dynamic Programming (Memoization) | O(n) | O(n) | Optimized recursion |
Command-line Approach (C) | O(n) | O(1) | Efficient for compiled languages |
The Fibonacci series is an essential concept in mathematics and programming, widely used in algorithms, problem-solving, and real-world applications. This article explored various methods to generate Fibonacci numbers up to a given value n
.