Kotlin is a modern, concise, and versatile programming language that can be used for a wide range of applications, including software development, web development, and Android app development.
In this tutorial, we’ll look at how to use Kotlin to find the factorial of a number using recursion.
Factorial is a mathematical concept that refers to the product of an integer and all the integers that come before it.
For instance, the factorial of 5 (written as 5!) is 5 * 4 * 3 * 2 * 1, which equals 120.
The most straightforward way to calculate the factorial of a number is to use a loop that multiplies each integer by the previous one until you reach the target number.
However, we can also use recursion to find the factorial of a number.
Recursion is a programming technique that involves a function calling itself repeatedly until a specific condition is met.
To find the factorial of a number using recursion in Kotlin, we’ll create a function that takes an integer as an argument and returns its factorial.
Here’s the code:
fun factorial(n: Int): Int { return if (n == 1) { n } else { n * factorial(n - 1) } }
In this function, we use the “if” statement to check whether the number is 1.
If it is, we simply return 1 because the factorial of 1 is 1. If the number is not 1, we multiply it by the result of calling the same function with the argument of n-1.
This way, the function keeps calling itself with decreasing integers until it reaches 1 and returns the final result.
To test this function, we can call it with a number and print the result. For example, if we want to find the factorial of 5, we can do:
fun main() { val number = 5 val result = factorial(number) println("The factorial of $number is $result") }
When we run this program, we should see the following output:
The factorial of 5 is 120
In conclusion, we can use recursion to find the factorial of a number in Kotlin.
The code is concise and straightforward, and it can be easily adapted for other programming languages that support recursion.