Kotlin – Find factorial of a number

Find Factorial of a Number in Kotlin

In this tutorial, you will learn how to calculate the factorial of a given number using Kotlin.

The factorial of a number is the product of all positive integers from 1 to that number. In Kotlin, you can use a loop to calculate the factorial of a given number. This process involves multiplying the current number with the previous result as you iterate through the numbers.

Example

Calculate Factorial

We’ll start with an example of calculating the factorial of a number:

Factorial of a number is the product of all positive integers from 1 to that number.

In this example, the calculateFactorial() function uses a loop to calculate the factorial of the given number. The result is the product of all positive integers from 1 to the given number.

Kotlin Program

// Function to calculate factorial
fun calculateFactorial(number: Int): Long {
    var factorial = 1L
    for (i in 1..number) {
        factorial *= i
    }
    return factorial
}

fun main() {
    val number = 5
    val result = calculateFactorial(number)
    println("Factorial of $number is: $result")
}

Output

Factorial of 5 is: 120

Summary

In this Kotlin Tutorial, we learned how to find the factorial of a given number in Kotlin, with the help of example programs.