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

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

Announcement: The Most Exciting Thing I've Done

Today, I'm announcing the most exciting project I've been involved with. It's called CrowdSync, and it helps to automate paperwork, communication and logistics when dealing with groups of people. Read on for why this is so big.

Three Ways to Start Talking to Users

How to Post to Private Slack Channels from Zapier

If you automate posting to Slack via Zapier, you might need to post to a private channel. It's not entirely obvious how to do it, but actually pretty damn easy.

A Peek Inside our UX Process