Scala function: Calculate the factorial of a number
Scala Function Exercise-1 with Solution
Write a Scala function to calculate the factorial of a given number.
Sample Solution:
Scala Code:
object FactorialCalculator {
def factorial(n: Int): BigInt = {
if (n == 0 || n == 1) {
1
} else {
n * factorial(n - 1)
}
}
def main(args: Array[String]): Unit = {
val number = 4
val result = factorial(number)
println(s"The factorial of $number is: $result")
val number1 = 10
val result1 = factorial(number1)
println(s"The factorial of $number1 is: $result1")
}
}
Sample Output:
The factorial of 4 is: 24 The factorial of 10 is: 3628800
Explanation:
In the above exercise -
- The factorial method uses a recursive approach to calculate the factorial. If the input n is 0 or 1, the method returns 1. Otherwise, it recursively calls itself with the parameter n - 1 and multiplies it by n.
- The main method is also defined inside the FactorialCalculator object. It serves as the program's entry point.
- Inside the main method, there are two variables declared: number with a value of 4 and number1 with a value of 10.
- The factorial method is called with number and number1 as arguments, and the results are stored in the result and result1 variables, respectively.
- Finally, the program prints the factorial results using println statements, along with the corresponding numbers.
Scala Code Editor :
Previous: Scala Function Exercises Home.
Next: Determine if a number is prime.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/function/scala-function-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics