Scala program to find Factorial of a number
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 above approach
Example :
// 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 )) } } |
120
Method 2 : Use of Recursion
In this method, Recursive formula N! = N * (N -1) ! is used to calculate the factorial of the given number.
Below is the implementation of above approach.
Example :
// 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 )) } } |
120
Recommended Posts:
- Program to print Java Set in Scala
- Program to convert Java Set to an Iterator in Scala
- Program to convert Java list to Seq in Scala
- Program to convert Java Set to Stream in Scala
- Program to convert Java Set to a String in Scala
- Program to convert Java Set to Sequence in Scala
- Program to print Java Set of Strings in Scala
- Program to convert Java Set to a Vector in Scala
- Program to convert Java Set to List in Scala
- Program to convert Java list to Set in Scala
- Program to print Java Set of characters in Scala
- Program to convert Java Set to a Traversable in Scala
- Program to print Java List in Scala
- Program to convert Java list to an iterator in Scala
- Program to convert Java list to Traversable in Scala
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.