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:
Approach 1: Using for loop
Example: This example uses for loop to print the Fibonacci series.
javascript
function fibonacci(num) {
let num1 = 0;
let num2 = 1;
let sum;
let i = 0;
for (i = 0; i < num; i++) {
sum = num1 + num2;
num1 = num2;
num2 = sum;
}
return num2;
}
console.log( "Fibonacci(5): " + fibonacci(5));
console.log( "Fibonacci(8): " + fibonacci(8));
|
Output:
Fibonacci(5): 3
Fibonacci(8): 13
Example: This example uses a while loop to print the Fibonacci series.
javascript
function fibonacci(num) {
if (num == 1)
return 0;
if (num == 2)
return 1;
let num1 = 0;
let num2 = 1;
let sum;
let i = 2;
while (i < num) {
sum = num1 + num2;
num1 = num2;
num2 = sum;
i += 1;
}
return num2;
}
console.log( "Fibonacci(5): " + fibonacci(5));
console.log( "Fibonacci(8): " + fibonacci(8));
|
Output:
Fibonacci(5): 3
Fibonacci(8): 13
Approach 3: using recursion
As we know that the nth Fibonacci number is the summation of n-1 and n-2 term and the n-1 term is the summation of n-2 and n-3 terms. So, to get the nth Fibonacci term we can follow fib(n)=fib(n-1)+fib(n-2) fib(n)=fib(n-2)+fib(n-3)+fib(n-3)+fib(n-4) …. fib(n)=fib(1)+fib(0)+fib(1)+fib(0)+fib(1)+fib(0)….fib(1)+fib(0) [terms containing sum of fib(1) and fib(0) fib(1)=0 fib(2)=1
Example: This example shows the use of the above approach.
javascript
function fibonacci(num) {
if (num == 1)
return 0;
if (num == 2)
return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}
console.log( "Fibonacci(5): " + fibonacci(5));
console.log( "Fibonacci(8): " + fibonacci(8));
|
Output:
Fibonacci(5): 3
Fibonacci(8): 13
Last Updated :
13 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...