Approach 3 Using Generator Function
Using a generator function, Fibonacci numbers are yielded incrementally. It maintains two variables representing the current and previous Fibonacci numbers. With each iteration, the next Fibonacci number is calculated and yielded, allowing for efficient memory usage and on-demand generation of the series.
Example:
function* fibonacciGenerator(num) {
let num1 = 0;
let num2 = 1;
yield num1;
yield num2;
for (let i = 3; i <= num; i++) {
let sum = num1 + num2;
num1 = num2;
num2 = sum;
yield num2;
}
}
function fibonacci(num) {
let result;
const iterator = fibonacciGenerator(num);
for (let i = 0; i < num; i++) {
result = iterator.next().value;
}
return result;
}
console.log("Fibonacci(5): " + fibonacci(5));
console.log("Fibonacci(8): " + fibonacci(8));
Output
Fibonacci(5): 3 Fibonacci(8): 13
JavaScript Program to print Fibonacci Series
The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms.
The sequence Fn of Fibonacci numbers is defined by the recurrence relation:
Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1
Examples:
Input : 5
Output : 8
Input :8
Output :34
There are three methods to print the Fibonacci series, which are described below:
Table of Content
- Approach 1: Using For loop
- Approach 2: Using While loop
- Approach 3: Using Recursion
- Approach 3: Using Generator Function: