Scala program to find Factorial of a number
Last Updated :
05 Jan, 2023
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
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
object GFG
{
def factorial(n : Int) : Int = {
var f = 1
for (i <- 1 to n)
{
f = f * i;
}
return f
}
def main(args : Array[String])
{
println(factorial( 5 ))
}
}
|
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
object GFG
{
def factorial(n : Int) : Int =
{
if (n == 0 )
return 1
else
return n * factorial(n- 1 )
}
def main(args : Array[String])
{
println(factorial( 5 ))
}
}
|
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.
Share your thoughts in the comments
Please Login to comment...