Having issue with Tail Recursion function

I just fixed a couple of typos in your code and this seems to work:

import scala.io.StdIn

object TailRecursion2 {
  def factorial(number: Int): Int = {
    @annotation.tailrec
    def factorialWithAccumulator(accumulator: Int, number: Int) : Int =
      if (number == 1) accumulator
      else factorialWithAccumulator(accumulator * number, number - 1)

    factorialWithAccumulator(accumulator = 1, number)
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val input1 = StdIn.readInt()
    println(TailRecursion2.factorial(input1))
  }
}
1 Like

Thanks
The code is working fine

Hello Im getting the error as type mismatch at the last line.
Can you plz help me in this

How to write this code, anyone help.

Can you paste your code (within a fenced code block) and give the precise error message. Then someone should be able to help.

regards,
Siddhartha

2 Likes
object Result {

    /*

     * Complete the 'factorial' function below.

     *

     * The function accepts INTEGER input1 as parameter.

     */

      def factorial(n: Int) =

    {  

        // Put your code here

        def iter(n:Int,accum:Int):Int = 

            if(n==0) accum else iter(n-1,n*accum)

        iter(n,1)  

    }

    

}

Im also not getting any output in the stdout. How to solve this, anyone help. What is wrong in it