The optimal method for computing the Fibonacci sequence using JavaScript

Improving my skills in optimizing algorithms and understanding big-o notation is a priority for me.

I devised the following function to compute the n-th Fibonacci number. It works well for higher inputs, but I wonder how I can enhance it. What are the downsides of calculating the Fibonacci sequence in this manner?

function fibo(n) {  

    var i;
    var resultsArray = [];  

    for (i = 0; i <= n; i++) {
        if (i === 0) {
            resultsArray.push(0);
        } else if (i === 1) {
            resultsArray.push(1);
        } else {
            resultsArray.push(resultsArray[i - 2] + resultsArray[i - 1]);
        }
    }

    return resultsArray[n];
}

I suspect that my time complexity is O(n), while the space complexity could be O(n^2) due to the array creation. Is my analysis correct?

Answer №1

By avoiding the use of an Array, you can optimize memory usage and reduce the number of .push calls needed

function fibonacci(n) {
    var first = 0, second = 1, result;
    if (n < 3) {
        if (n < 0) return fibonacci(-n);
        if (n === 0) return 0;
        return 1;
    }
    while (--n)
        result = first + second, first = second, second = result;
    return result;
}

Answer №2

Fibonacci Performance Test:

    var memo = {};
    var countInteration = 0;
    var fib = function (n) {
        if (memo.hasOwnProperty(n)) {
            return memo[n];
        }
        countInteration++;
        console.log("Iteration = " + n);
        if (n == 1 || n == 2) {
            result = 1;
        } else {
            result = fib(n - 1) + fib(n - 2);
        }
        memo[n] = result;
        return result;
    }
    //output `countInteration` = parameter `n`

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for verifying that a file has not been selected in Croppie

Whenever I use croppie to crop images on my website, everything works fine when I select an image and upload it. But if I try to crop and upload without selecting an image, a black image gets uploaded instead. How can I validate if the file upload is empty ...

activating javascript function in rails when the page reloads

I have a rails4 app and I'm looking to implement some specific JavaScript events when the page loads, but only if the user is coming from a certain page. On the post#index page, all comment replies are initially hidden. When a user clicks on a specif ...

What is the best way to determine the quantity of elements received from an ajax request?

Here's the method I am currently using to count the number of li elements returned from an AJAX call: $.post('@Url.Action("actionName", "controller")', function (data) { $('#notificationCounter').html($(data).find('li&a ...

How to switch the code from using $.ajax() to employing $.getJSON in your script

How can I convert this code from using AJAX to JSON for better efficiency? AJAX $('#movie-list').on('click', '.see-detail', function() { $.ajax({ url: 'http://omdbapi.com', dataType: 'json', d ...

The process of incorporating the dymo.framework into an Angular project

My Angular project is currently in need of importing dymo.connect.framework. However, I am facing some challenges as the SDK support provided by dymo only explains this process for JavaScript. I have also referred to an explanation found here. Unfortunate ...

Leveraging v-for within a component that incorporates the <slot/> element to generate a versatile and interactive Tab menu

Currently, I am in the process of developing a dynamic tab menu using Vue 3 and slots. Successfully implementing tabs, I have created BaseTabsWrapper and BaseTab components. The challenge lies in using v-for with the BaseTab component inside a BaseTabsWrap ...

Retrieving values of checked boxes in a table using JavaScript

While using the select method, I had this line of code: Person_name = $('#selectedPerson').val() When selecting 2 values, person_name.length displays as 2. Recently, I switched to checkboxes displayed in a table. However, when I use person_name ...

``Next.js allows you to nest components within a component to create routing functionalities

My login page has 3 different roles for logging in: Admin, Student, and Company. Instead of redesigning the entire page, I just want to update the login component for each specific role. Login Page export default function Authpage(){ return( ...

Revitalizing and rerouting page upon button click

The issue at hand is: When the "Post now" button is clicked, the modal with the filled form still appears. If the button is clicked again, it adds the same data repeatedly. I aim to have the page refresh and navigate to a link containing the prediction d ...

Updating switch data on click using Vuejs: A step-by-step guide

Could someone please explain to me how to swap two different sets of data when clicked? For instance, let's say we have the following data: data() { return { data_one: [ { name: "Simo", ...

Can't get className to work in VueJS function

I need help changing the classNames of elements with the "link" class. When I call a method via a click action, I can successfully get the length of the elements, but adding a class does not seem to work. Does anyone have any insights into this issue? HTM ...

Make a quick call to the next function within the error handling module for a

Currently, I am facing an issue while trying to call the next function within the error handler of my node + express js application. In each controller, I have a middleware known as render which is invoked by calling next, and I wish to achieve the same f ...

Gulp does not generate any new folders

Currently, my workspace is located in a directory named "Super gulp" with other directories that contain my files. The issue I'm facing is related to converting my .pug files into HTML files and placing them in the "goal" directory. However, when I tr ...

Using React to access the properties of objects within an array that has been dynamically mapped

For my initial dive into developing a React application, I am currently in the process of fetching data from a database and updating the state to store this information as an array. My main challenge lies in accessing the properties of the objects within t ...

Utilizing socket.io to access the session object in an express application

While utilizing socket.io with express and incorporating express session along with express-socket.io-session, I am encountering difficulty in accessing the properties of the express session within the socket.io session object, and vice versa. const serve ...

Ways to detect the use of vue.js on a webpage without relying on vue-devtools

One way to determine if the page is utilizing Angular or AngularJS is by inspecting window.ng and window.angular. Is there a similar method to identify whether Vue is being used on the page directly from the console, without relying on vue-devtools? ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

What method can I use in pure Javascript to identify which day the week begins on, either Monday or Sunday, based on the

Can someone help me determine the start day of the week in local time using only Javascript? The start day could be Monday, Sunday, Saturday, or Friday. I came across this helpful resource on Stack Overflow: <firstDay day="mon" territories="001 AD AI ...

A tool that enhances the visibility and readability of web languages such as HTML, PHP, and CSS

Looking to organize my own code examples, I need a way to display my code with syntax highlighting. Similar to how Symfony framework showcases it on their website: http://prntscr.com/bqrmzk. I'm wondering if there is a JavaScript framework that can a ...

The function Amplify.configure does not exist

Currently attempting to utilize AWS Amplify with S3 Storage, following the steps outlined in this tutorial for manual setup. I have created a file named amplify-test.js, and here is its content: // import Amplify from 'aws-amplify'; var Amplify ...