Kotlin: Calculate the Factorial of a Number

1. Introduction

Kotlin's expressive and succinct syntax, combined with its robust standard library, makes it a preferred choice for a plethora of programming tasks. Among its myriad applications, mathematical computations stand out. In this blog post, we're diving into a foundational mathematical concept: calculating the factorial of a number using Kotlin.

2. Program Overview

This Kotlin piece will:

1. Prompt the user to submit a number.

2. Capture the specified number.

3. Compute the factorial of the number.

4. Display the calculated factorial to the user.

3. Code Program

import java.util.Scanner

fun main() {
    // Initiate Scanner for collecting user input
    val reader = Scanner(System.in)

    // Ask the user to provide a number
    print("Enter a non-negative integer to compute its factorial: ")

    // Store the provided number
    val num = reader.nextInt()

    // Ensure the entered number is non-negative
    if (num < 0) {
        println("Please provide a non-negative number.")

    // Compute the factorial of the number
    val factorial = computeFactorial(num)

    // Present the calculated factorial to the user
    println("The factorial of $num is: $factorial")

// Recursive function to compute factorial
fun computeFactorial(n: Int): Long {
    return if (n == 0) 1 else n * computeFactorial(n - 1)


Enter a non-negative integer to compute its factorial: 5
The factorial of 5 is: 120

4. Step By Step Explanation

1. Scanner Setup: We harness the Scanner class from java.util package for capturing user input. Our instance is named reader.

2. Number Input: The user is prompted via the print function to submit a number, which gets stored in num.

3. Non-negative Check: Factorials are defined for non-negative integers. Thus, the program checks if the user's input is negative and notifies the user accordingly.

4. Factorial Calculation: The program calls the computeFactorial function to obtain the factorial value. This function is recursive: it calls itself with decremented values until it reaches zero. Once zero is reached, the function returns 1, creating a chain of multiplications to give the factorial of the initial number.

5. Result Display: The println function illustrates the factorial result to the user.