# 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.

Contents

## 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)  ``

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.

• 0 < N <= 40

## Output Format

Output one integer, theÂ NthÂ Fibonacci number.

=== codingbroz.com_728x90 (#88864) ===
=== codingbroz.com_728x90 (#88864) ===

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 **/