.Js
Generate the Fibonacci series up to a certain number:
You can create a JavaScript function to generate the Fibonacci series up to a certain number by iteratively calculating each Fibonacci number until it exceeds the specified limit. Here's how you can implement it:
function generateFibonacci(limit) { // Initialize Fibonacci series with the first two numbers const fibonacciSeries = [0, 1]; let i = 2; while (true) { const nextFibonacci = fibonacciSeries[i - 1] + fibonacciSeries[i - 2]; if (nextFibonacci > limit) { break; } fibonacciSeries.push(nextFibonacci); i++; } return fibonacciSeries; } // Example usage: const limit = 50; // Generate Fibonacci series up to 50 const fibonacciSeries = generateFibonacci(limit); console.log(fibonacciSeries); // Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
Explanation:
1. We start with an array containing the first two Fibonacci numbers: 0 and 1.
2. We then calculate subsequent Fibonacci numbers by adding the last two numbers in the series.
3. The loop continues until the next Fibonacci number exceeds the specified limit.
4. The function returns the generated Fibonacci series up to the limit.
Note: You can adjust the 'limit' variable to specify the desired upper limit for the Fibonacci series.
• Learn in-depth concepts of fibonacci series from the algorithm page.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.