Open In App

Scala program to find Factorial of a number

Improve
Improve
Like Article
Like
Save
Share
Report

Given a number N, the task is to calculate factorial of N. In mathematics, the factorial of a positive integer N is the product of all positive integers less than or equal to N. The recursive formula to calculate factorial of a given positive integer N is

N! = N * ( N -1 )! 
N! = 1 if N = 1 or N = 0

Factorial of a number Examples:

Input : N = 3 
Output : 6

Input : N = 5
Output : 120

Method 1 : Iterative Way In this method, we will use a loop to iterate over the sequence of numbers to get the factorial. 

Below is the implementation of the above approach 

Scala




// Scala Program to calculate
// Factorial of a number
 
// Creating object
object GFG
{
    // Iterative way to calculate
    // factorial
    def factorial(n: Int): Int = {
         
        var f = 1
        for(i <- 1 to n)
        {
            f = f * i;
        }
         
        return f
    }
 
    // Driver Code
    def main(args: Array[String])
    {
        println(factorial(5))
    }
 
}


Output :

120

Time Complexity:  O(n) because the for loop iterates n times.
Auxiliary Space:  O(1) because the only variable being used is a single integer (f) which remains constant regardless of the input size.

Method 2: Use of Recursion In this method, the Recursive formula N! = N * (N -1) ! is used to calculate the factorial of the given number. Below is the implementation of the above approach. 

Scala




// Scala Program to calculate Factorial
// of a number using recursion
 
// Creating object
object GFG
{
    // Function to calculate
    // factorial using Recursive
    // formula (i.e N! = N * N-1 !)
    def factorial(n: Int): Int =
    {
        if (n == 0)
            return 1
        else
            return n * factorial(n-1)
    }
 
    // Driver Code
    def main(args: Array[String])
    {
        println(factorial(5))
    }
}


Output :

120

Time Complexity:  O(n), where n is the number of recursive calls. This is because the factorial() function calls itself recursively n times to calculate the factorial of a given number. As a result, the time complexity is linear in the input size.
Auxiliary Space: O(n), where n is the number of recursive calls. This is because in each recursive call, a new stack frame is created to store the local variables and the return address.



Last Updated : 05 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads