w3resource

Scala Program: Calculate the factorial with MathUtils Object

Scala OOP Exercise-3 with Solution

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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/oop/scala-oop-exercise-3.php