w3resource

Scala function: Calculate the factorial of a number


Write a Scala function to calculate the factorial of a given number.


Pre-Knowledge (Before you start!)

  • Basic Scala Syntax: Familiarity with writing and running Scala programs.
  • Functions in Scala: Understanding how to define and call functions, including recursive functions.
  • Recursive Functions: Knowledge of recursion and base cases to solve problems like factorial calculation.
  • BigInt Type: Awareness of the BigInt type for handling large numbers that exceed the range of standard numeric types.
  • Conditional Statements: Ability to use if/else statements for decision-making in recursive logic.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Factorial Function: Create a recursive function named "factorial" that takes an integer as input and returns its factorial as a BigInt.
  • Base Case: Check if the input number is 0 or 1. If true, return 1, as the factorial of 0 and 1 is 1.
  • Recursive Case: For numbers greater than 1, multiply the current number by the factorial of the number minus 1 (n - 1).
  • Call the Function: In the main method, test the "factorial" function by passing different integers, such as 4 and 10, and store the results in variables.
  • Display the Output: Use println() to print the factorial results in a readable format, including the input number in the output message.
  • Test with Different Numbers: Change the input values to verify the program works for various cases, including edge cases like 0 or large numbers.

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?



Follow us on Facebook and Twitter for latest update.