Scala Program: Calculate the factorial with MathUtils Object
Write a Scala program that creates an object MathUtils with a static method factorial that calculates the factorial of a given number.
Sample Solution:
Scala Code:
object MathUtils {
def factorial(n: Int): BigInt = {
if (n == 0 || n == 1) {
1
} else {
n * factorial(n - 1)
}
}
}
object Main {
def main(args: Array[String]): Unit = {
val number1 = 4
val result1 = MathUtils.factorial(number1)
println(s"The factorial of $number1 is: $result1")
val number2 = 10
val result2 = MathUtils.factorial(number2)
println(s"The factorial of $number2 is: $result2")
}
}
Sample Output:
The factorial of 4 is: 24 The factorial of 10 is: 3628800
Explanation:
In the above exercise -
The "MathUtils" object contains the factorial method. This method calculates the factorial of a given number using recursion. If the number is 0 or 1, it returns 1. Otherwise, it recursively calls itself with n - 1 and multiplies the result by n.
The "Main" object contains the main method where you can test the factorial method. In this example, it calculates the factorial of the number 4 and 10 and prints the result.
Scala Code Editor :
Previous: Create student subclass with grade property.
Next: Abstract shape class with rectangle and circle subclasses.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics