In this tutorial, you shall learn how to write a program to find the factorial of a given number in Kotlin.

Kotlin – Factorial

To find the factorial of a given number in Kotlin, we can use recursion function.

The factorial of a number n is defined as the following.

n! = 1*2*3*...*n

Program

ADVERTISEMENT

1. Find factorial using recursion technique

In the following program, we read a number from user, calculate the factorial of this number using recursion function. We define the recursion function factorial(). This function returns 1 if the argument is zero, else it returns the product of given number and the factorial of the (number-1).

Main.kt

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

fun main() {
    print("Enter an integer : ")
    val num = readLine()!!.toInt()
    val result = factorial(num)
    println("$num! is $result.")
}

Output #1

Enter an integer : 5
5! is 120.

Output #2

Enter an integer : 10
10! is 3628800.

2. Find factorial using For loop statement

In the following program, we use For loop to calculate the factorial of given number.

Main.kt

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

fun main() {
    print("Enter an integer : ")
    val num = readLine()!!.toInt()
    val result = factorial(num)
    println("$num! is $result.")
}

Output #1

Enter an integer : 5
5! is 120.

Output #2

Enter an integer : 10
10! is 3628800.

Reference tutorials for the program

Conclusion

In this Kotlin Tutorial, we learned how to find the factorial of a given number using recursion technique, or For loop statement.