×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala program to find factorial of a number

Scala | Finding factorial of a Number: Here, we are going to learn how to find factorial of a given number in Scala programming language?
Submitted by Shivang Yadav, on April 21, 2020 [Last updated : March 09, 2023]

Scala – Find the Factorial of a Number

Factorial

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

1. Using Recursive Approach

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:

Scala code to find factorial using recursive approach

object MyObject {

    // Recursive function to calculate factorial
    def factorialRec(n: Int): Int = {
        if (n <= 1)
            1
        else
            n * factorialRec(n - 1)
    }

    // Main method
    def main(args: Array[String]): Unit = {
        val n = 6
        println("The factorial of " + n + " is " + factorialRec(n))
    }
}

Output

The factorial of 6 is 720

2. Using Iterative Approach

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

Scala code to find factorial using iterative approach

object MyObject {
    // Iterative method to calculate factorial
    def factorialIt(n: Int): Int = {
        var factorial = 1
        for (i <- 1 to n)
            factorial *= i
        factorial // Return the result
    }

    // Main method
    def main(args: Array[String]): Unit = {
        val n = 6
        println("The factorial of " + n + " is " + factorialIt(n))
    }
}

Output

The factorial of 6 is 720

Scala Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.