Determine if a number is in the Fibonacci series using JavaScript


I recently had a conversation with a buddy of mine who is a kick ass dev. We had been chatting about working on little academic problems, as a way to increase your understanding of code and algorithms. Since we usually build for the web, where things are much more practical, spending some time on contrived problems like this is challenging and helps you think more deeply about solving problems using code.

So, we started tinkering with a question he was asked in an interview recently. How would you find out if a number is in the Fibonacci series? You can’t simply match against the entire series, as theoretically, the series is infinite, and you’d run out of memory.

I worked up a solution using Javascript that looks like this:

function isFib(val){
 var prev = 0;
 var curr = 1;
 while(prev<=val){
   if(prev == val){
     console.log("yes!");
     return;
   }
   curr = prev + curr;
   prev = curr - prev;
 }
console.log("nope");

isFib(89); //for example, check if 89 is in the series

This solution essentially crawls through the series, looking for a match against the value given when calling the function. It should be fairly memory conservative, as we’re only storing the current and previous values of the walk. It’s also quite fast.

How would you improve this? Can this be made more efficient? Give your suggestions in the comments!

For more awesome little challenges like this, check out HackerRank.

Related Posts

Default Yes vs. Default No

Are you and your team members default yes, or default no? One is good for startups, the other not so much.

Check Your Echo Chamber

The people you surround yourself with create your reality. Choose carefully.

Don't Forget the Goal

There's only one thing that matters when you're building software.

How To Get a Job Offer

Want to get a job in the field you love easily? This is how.

Required Reading for All Couples

If you're married, about to get married, or just committed to someone for a long period of time, these three books are absolutely required reading.

I Launched a New Podcast, and I Want You to Call In

I just launched a new podcast called Design By Committee, dedicated to answering your questions about UX, product design, content, strategy and anything else tech.

Shitty Sales Have Made Product Development Harder

Shitty, one-sided sales processes have made product development much more difficult for early stage startups.

Why I'm Cold Emailing You

You might have gotten a cold email from me. Tasteless? Some people think so. Here's why I'm doing it.

How I Found Your Email

I've been cold emailing a lot of people, and many folks are surprised that I found their email. Here's where I dug it up.

Sales is User Research, Undercover