Q:

Scala program to find factorial of a number

belongs to collection: Scala Basic Programs

0

Factorial of a number(n!) is the product of all positive numbers less than or equal to that number.

The formula for factorial of a number is,

    n! = n * (n-1) * (n-2) * ... * 2 * 1
    n! = 1 if n = 1 or 0

Based on the above formula we can generate a recursive formula,

    n! = n * (n-1)! 

Given a number, we have to find its factorial.

Example:

    Input: 
    n = 6

    Output: 
    n! = 720 

    Explanation:
    6! = 6*5*4*3*2*1 = 720

The program will use this formula to find the factorial. As find factorial is a repetitive process. We have two methods to solve this problem,

  1. Using iteration
  2. Using recursion

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

1) Recursive Approach to find factorial of a number

In recursion, we will call the same method multiple times until a condition is not satisfied.

Here, we will call the function factorial(n) in the following way:

Program:

object myObject {

    def factorialRec(n: Int): Int ={
        if(n <= 1)
            return 1
        return n * factorialRec(n-1)
    }
    
    def main(args: Array[String]) {
        val n = 6
        println("The factorial of " + n + " is " + factorialRec(n))
    }
}

Output

The factorial of 6 is 720

2) Iterative approach to find factorial of a number

In iteration, we will loop over a sequence of numbers and multiply the number to result variable to find factorial.

Program:

object myObject {
    def factorialIt(n: Int): Int ={
       var factorial = 1
       for(i <- 1 to n)
            factorial *= i
        return factorial
    }
    
    def main(args: Array[String]) {
        val n = 6
        println("The factorial of " + n + " is " + factorialIt(n))
        
    }
}

Output

The factorial of 6 is 720

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< Scala program to demonstrate the 1\'s complem...