Fibonacci Program Using Recursion in Scala

9/3/2021
All Articles

#Fibonacci Program Using Recursion in Scala #Scala #Recursion #Program #factorial program in scala

Fibonacci Program Using Recursion in Scala

Fibonacci Program Using Recursion in Scala | fibonacci scala  program

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding numbers ones. 
The sequence starts with 0 and 1, 
and then each subsequent number is the sum of the two previous numbers. The Fibonacci series is look like  this:
 
0, 1, 2, 3, 4, 5, 6, 7,   8,   9,  10,  11, 12 
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...

Let's See the Fibonacci Program Using Recursion in Scala.

To generate the Fibonacci series, you can use a loop or a recursive function and pattern matching.

Example 1 with pattern matching


def fib1( n : Int) : Int = n match {
   case 0 | 1 => n
   case _ => fib1( n-1 ) + fib1( n-2 )
}

Example 2 with Recursion

 

package com.developerIndian.usecase
 
class FibonacciDemo {
 
}
object FibonacciDemo{
 
    def fibonacci(n: Int): Int = {
      if (n <= 0) {
        throw new IllegalArgumentException("Input is always positive integer.")
      } else if (n == 1 || n == 2) {
        1
      } else {
        fibonacci(n - 1) + fibonacci(n - 2)
      }
    }
 
    def main(args: Array[String]): Unit = {
      try {
        val n = 12 // Fibonacci for a different number.
        println(s"The ${n}th Fibonacci number is: ${fibonacci(n)}")
      } catch {
        case ex: IllegalArgumentException =>
          println(ex.getMessage)
      }
    }
  }

 

 

Conclusion :

Although straightforward, the recursive method can lose efficiency for bigger values of n because it involves repeated calculations. 
Memorization or dynamic programming techniques can be used to store interim findings and reduce the need for repeated computations.
 
This Solution is provided by Shubham mishra This article is contributed by Developer Indian team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.Also folllow our instagram , linkedIn , Facebook , twiter account for more

Article