Skip to main content

How to calculate the factorial of a number using recursion in Kotlin

How to calculate the factorial of a number using recursion in Kotlin.

Here's a detailed step-by-step tutorial on how to calculate the factorial of a number using recursion in Kotlin.

What is factorial?

Factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 5 is calculated as 5! = 5 * 4 * 3 * 2 * 1 = 120.

Using recursion to calculate factorial

Recursion is a technique in programming where a function calls itself to solve a smaller subproblem of the same type. In the case of calculating factorial, we can define a recursive function that calls itself to calculate the factorial of a smaller number until it reaches the base case.

Here's the step-by-step process to calculate the factorial of a number using recursion in Kotlin:

  1. Define a function called factorial that takes an integer n as input and returns the factorial of n.
  2. In the factorial function, define a base case to handle the smallest possible input. If n is 0 or 1, return 1, as the factorial of 0 or 1 is 1.
  3. If n is greater than 1, recursively call the factorial function with n-1 as the input and multiply the result with n.
  4. Return the result of the multiplication as the factorial of n.

Let's see the implementation of the factorial function using recursion in Kotlin:

fun factorial(n: Int): Int {
if (n == 0 || n == 1) {
return 1
}
return n * factorial(n - 1)
}

Example usage

Now, let's see how we can use the factorial function to calculate the factorial of a number. We can call the function with any non-negative integer as the input.

fun main() {
val number = 5
val result = factorial(number)
println("The factorial of $number is $result")
}

Output:

The factorial of 5 is 120

Handling edge cases

It's important to handle edge cases when using recursion. In the case of calculating factorial, we need to handle negative numbers and large numbers that may cause integer overflow.

To handle negative numbers, we can add a check at the beginning of the factorial function to return an error message if n is less than 0.

To handle large numbers, we can use the BigInteger class from the Kotlin standard library instead of Int. BigInteger can handle arbitrarily large integers.

Here's an example of how to handle negative numbers and large numbers:

import java.math.BigInteger

fun factorial(n: Int): BigInteger {
if (n < 0) {
throw IllegalArgumentException("Factorial is not defined for negative numbers")
}
if (n == 0 || n == 1) {
return BigInteger.ONE
}
return BigInteger.valueOf(n.toLong()) * factorial(n - 1)
}

Now, the factorial function can handle negative numbers and large numbers without any issues.

That's it! You now know how to calculate the factorial of a number using recursion in Kotlin.