Skip to main content

How to calculate the factorial of a number in Kotlin

How to calculate the factorial of a number in Kotlin.

Here's a step-by-step tutorial on how to calculate the factorial of a number in Kotlin:

Step 1: Understanding Factorials

Before we dive into the code, let's understand what factorials are. In mathematics, the 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, 5! (read as "5 factorial") is calculated as 5 4 3 2 1, which equals 120.

Step 2: Writing the Factorial Function

Now, let's start coding. Open your favorite Kotlin IDE or create a new Kotlin file. We'll define a function called factorial that takes an integer parameter n and returns the factorial of that number.

fun factorial(n: Int): Long {
var result: Long = 1
for (i in 1..n) {
result *= i
}
return result
}

In the above code, we initialize the result variable to 1, as the factorial of 0 is defined as 1. We then use a for loop to iterate from 1 to n, multiplying result by each number in the range.

Step 3: Calling the Factorial Function

To test our factorial function, let's call it with different numbers and print the results. Add the following code to the main function:

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

In the above code, we define a variable number and assign it the value of the number for which we want to calculate the factorial (in this case, 5). We then call the factorial function with number as the argument and store the result in the factorialResult variable. Finally, we print the result using string interpolation.

Step 4: Running the Code

You can now run the code and see the output. The program will calculate the factorial of the number you provided and print it to the console. In our example, the output will be:

The factorial of 5 is 120

Step 5: Handling Edge Cases

Our current implementation works fine for positive integers. However, it does not handle edge cases such as negative numbers or very large numbers that may cause overflow. To handle these cases, we need to add some checks to our code. Here's an updated version of the factorial function that includes these checks:

fun factorial(n: Int): Long {
if (n < 0) {
throw IllegalArgumentException("Factorial is not defined for negative numbers")
}

var result: Long = 1
for (i in 1..n) {
if (result > Long.MAX_VALUE / i) {
throw ArithmeticException("Factorial value is too large to calculate")
}
result *= i
}

return result
}

In the updated code, we first check if the given number n is negative. If it is, we throw an IllegalArgumentException with an appropriate error message. We also check for potential overflow by comparing the current result with Long.MAX_VALUE / i. If the multiplication would result in a value greater than Long.MAX_VALUE, we throw an ArithmeticException.

Conclusion

You have now learned how to calculate the factorial of a number in Kotlin. Remember to handle edge cases such as negative numbers and potential overflow to ensure your code is robust.