🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. This guide will walk you through how to write a JavaScript program to compute the Fibonacci sequence using both iterative and recursive methods.
Problem Statement
Create a JavaScript program that:
- Accepts an integer
n(the position in the Fibonacci sequence). - Returns the Fibonacci number at that position.
Example:
Input:
5Output:
5(The sequence is 0, 1, 1, 2, 3, 5)Input:
7Output:
13(The sequence is 0, 1, 1, 2, 3, 5, 8, 13)
Solution Steps
- Read Input: Accept or define the input position
ndirectly in the program. - Handle Base Cases: The first two Fibonacci numbers are
0and1. - Compute Fibonacci: Implement two methods—recursive and iterative—to compute the Fibonacci number.
- Display the Result: Output the Fibonacci number at position
nfor each method.
Method 1: Recursive Approach
// JavaScript Program to Find Fibonacci Number Using Recursion
// Author: https://www.javaguides.net/
function fibonacciRecursive(n) {
if (n === 0) return 0;
if (n === 1) return 1;
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
let position = 7; // Example input
let result = fibonacciRecursive(position);
console.log(`The Fibonacci number at position ${position} using recursion is: ${result}`);
Output:
The Fibonacci number at position 7 using recursion is: 13
Explanation:
- This function uses recursion to calculate the Fibonacci number. The base cases are
0and1for the first two Fibonacci numbers, and for larger values, it calls the function recursively to sum the previous two numbers.
Method 2: Iterative Approach
// JavaScript Program to Find Fibonacci Number Using Iteration
// Author: https://www.javaguides.net/
function fibonacciIterative(n) {
let a = 0, b = 1, next;
if (n === 0) return a;
for (let i = 2; i <= n; i++) {
next = a + b;
a = b;
b = next;
}
return b;
}
result = fibonacciIterative(position);
console.log(`The Fibonacci number at position ${position} using iteration is: ${result}`);
Output:
The Fibonacci number at position 7 using iteration is: 13
Explanation:
- The iterative approach uses a
forloop to calculate the Fibonacci number. Starting from0and1, the loop sums the two previous numbers and updates them until it reaches the desired position.
Method 3: Using Memoization (Optimized Recursion)
// JavaScript Program to Find Fibonacci Number Using Memoization
// Author: https://www.javaguides.net/
function fibonacciMemoization() {
const memo = {};
function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
if (memo[n]) return memo[n];
memo[n] = fib(n - 1) + fib(n - 2);
return memo[n];
}
return fib;
}
const fibonacci = fibonacciMemoization();
result = fibonacci(position);
console.log(`The Fibonacci number at position ${position} using memoization is: ${result}`);
Output:
The Fibonacci number at position 7 using memoization is: 13
Explanation:
- This optimized recursive approach uses memoization to store previously calculated Fibonacci numbers in a cache (
memo), reducing the time complexity from exponential to linear.
Conclusion
This JavaScript program demonstrates three methods for calculating Fibonacci numbers:
- Recursion is straightforward but inefficient for large numbers due to redundant calculations.
- Iteration is more efficient and uses less memory than recursion.
- Memoization combines recursion with caching, significantly improving performance for larger numbers.
Each method has its advantages, depending on the context in which you need to compute Fibonacci numbers.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment