Fibonacci Numbers – HackerRank Solution

In this post, we will solve Fibonacci Numbers HackerRank Solution. This problem (Fibonacci Numbers) is a part of HackerRank Functional Programming series.

Objective

In this challenge, we learn about using the Fibonacci Function.

Resources

The Fibonacci Series

The Fibonacci sequence begins with 0 and 1. These are the first and second terms, respectively. After this, every element is the sum of the preceding elements:

Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)  

Task

Given the starter code, complete the Fibonacci function to return the Nth term.

We start counting from Fibonacci (1) = 0. This might differ from some other notations that treats Fibonacci (0) = 0.

The overall equation is:

             = 0 , n = 1
Fibonacci(n) = 1 , n = 2
               Fibonacci(n-1) + Fibonacci(n-2)  , n > 2

Input Format

One line of input, the integer N.

Constraints

  • 0 < N <= 40

Output Format

Output one integer, the Nth Fibonacci number.

Sample Input

3  

Sample Output

1  

Function Prototype
The starter code is provided for Scala. The code for accepting the input and displaying the output is provided. You will be provided the input parameter N, and you need to return the Nth Fibonacci term.

Sample Input and Output Values for the Fibonacci Series

fibonacci(3) = (0+1) = 1  
fibonacci(4) = (1+1) = 2  
fibonacci(5) = (1+2) = 3  

Requirements
Simple test cases can be cleared with a purely recursive function exponentially. To clear the more challenging test cases without violating the principles of functional programming, you might benefit from learning about the accumulator technique.

Solution – Fibonacci Numbers – HackerRank Solution

Scala

object Solution {

  def fibonacci(x: Int): Int = x match {
    case 1 => 0
    case 2 => 1
    case _ => fibonacci(x - 1) + fibonacci(x - 2)
  }

  def main(args: Array[String]): Unit = {
    /** This will handle the input and output **/
    println(fibonacci(readInt()))
  }

  // readInt() is deprecated in Scala 13, but it is called by HackerRank's predefined code.
  // So it is added to fix the issue.
  def readInt(): Int = scala.io.StdIn.readInt()
}

Note: This problem (Fibonacci Numbers) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *