Find nth number in Fabonacci series

    0

    0

    package examples

    object fabonacci extends App {

    println("hello world")

    def fabon(n: Int): Int = { // loop on n values // Initialize sum at 1 // Each time go to next value if it is larger // Sum must be odd as Fibonacci series is odd // If n is even, reset and return last value // If it is not an odd number, reset and return the first value // return nth Fibonacci value def loop(x: Int, Last: Int, NextToLast: Int): Int = { // x is xth number I want to compute // Last is to keep fabonacci of n-1 and next to last to keep fabonacci n-2 // if (n <= 2) return 1 // else if (x >= n) return Last // else { //

    package examples
    
    object fabonacci extends App {
    
      println("hello world")
    
      def fabon(n: Int): Int = {
        def loop(x: Int, Last: Int, NextToLast: Int): Int = { // x is xth number I want to compute
          // Last is to keep fabonaci of n-1 and next to last to keep fabonaci n-2
          if (n <= 2) return 1
          else if (x >= n) return Last
          else {
            println("value of:" +x +"value of Last:" +Last + "value of :" +NextToLast)
            loop(x+1, Last + NextToLast, Last )
          }
        }
        //if (n <= 2) 1
        loop(2,1,1)
      }
    println(fabon(4))
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.