w3resource

Kotlin program: Calculate the factorial of a given number


Write a Kotlin program to find the factorial of a given number.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Variables and Data Types.
  • Conditional Statements.
  • Loops.
  • Factorial Concept.
  • String Interpolation.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Create a Factorial Function.
  • Use a Loop.
  • Return the Result.
  • Call the Function.
  • Display the Output.
  • Test with Different Numbers.
  • Common Errors to Avoid:
    • Forgetting edge cases like 0 or 1.
    • Using Int instead of Long for large results.
    • Misplacing logic in if-else or loops.

Sample Solution:

Kotlin Code:

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

fun calculateFactorial(number: Int): Long {
    return if (number == 0 || number == 1) {
        1
    } else {
        var result = 1L
        for (i in 2..number) {
            result *= i
        }
        result
    }
}

Sample Output:

Factorial of 5: 120

Explanation:

In the above exercise,

  • Inside the "main()" function, a variable named 'number' is declared and assigned a value of 5.
  • The calculateFactorial() function is then called with the number as an argument, and the result is stored in a variable named factorial.
  • Finally, the result is printed using string interpolation in the println() statement: "Factorial of $number: $factorial".

In the calculateFactorial() function,

  • The function takes an integer number as a parameter and returns the factorial as a Long value.
  • Inside the function, an if statement checks if the number is equal to 0 or 1. If it is, the function returns 1 because the factorial of 0 and 1 is 1.
  • If the number is greater than 1, the function initializes a variable result with 1L, indicating the starting value for the factorial calculation.
  • A for loop is used, starting from 2 (as the factorial calculation starts from 2) and continuing until number. In each iteration, the result is multiplied by i and assigned back to the result.
  • Finally, the calculated factorial is returned.

Go to:


PREV : Find maximum and minimum of three numbers.
NEXT : Check if a year is a leap year.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.