Calculating the factorial of a number is a common problem in computer science and mathematics. Factorials are used in permutations, combinations, and other mathematical computations. In this article, we will explore Kotlin Program to Find Factorial of a Number Using Recursion. Each example will be followed by its output and explanation.
Introduction
The factorial of a non-negative integer πn is the product of all positive integers less than or equal to πn. It is denoted by π!n! and is defined as:
π!=πΓ(πβ1)Γ(πβ2)Γβ¦Γ1
For π=0, 0!=1
Example 1: Basic Recursion
fun factorial(n: Int): Int {
return if (n == 0) 1 else n * factorial(n - 1)
}
fun main(args: Array<String>) {
val number = 5
val result = factorial(number)
println("Factorial of $number is $result")
}
1.2 Output
Factorial of 5 is 120
1.3 Explanation
In this example, the factorial
function uses a simple recursive approach. If πn is 0, it returns 1. Otherwise, it returns πn multiplied by the factorial of πβ1nβ1. This is a straightforward implementation of the mathematical definition of factorial.
Example 2: Tail Recursion
tailrec fun factorialTailRec(n: Int, accumulator: Int = 1): Int {
return if (n == 0) accumulator else factorialTailRec(n - 1, accumulator * n)
}
fun main(args: Array<String>) {
val number = 6
val result = factorialTailRec(number)
println("Factorial of $number is $result")
}
2.2 Output
Factorial of 6 is 720
2.3 Explanation
The factorialTailRec
function uses tail recursion to calculate the factorial. The tailrec
modifier tells the Kotlin compiler to optimize the recursive calls, preventing stack overflow for large inputs. The function uses an accumulator to carry the intermediate results, making the recursion tail-recursive.
Example 3: Recursive Factorial with Input Validation
3.1 Code
fun factorialWithValidation(n: Int): Int {
require(n >= 0) { "Number must be non-negative" }
return if (n == 0) 1 else n * factorialWithValidation(n - 1)
}
fun main(args: Array<String>) {
val number = 7
val result = factorialWithValidation(number)
println("Factorial of $number is $result")
}
3.2 Output
Factorial of 7 is 5040
3.3 Explanation
In this example, the factorialWithValidation
function includes input validation to ensure that the input number is non-negative. If the input is negative, it throws an IllegalArgumentException
. This helps in making the function more robust by handling invalid inputs gracefully.
Conclusion
We have discussed three different approaches to find the factorial of a number using recursion in Kotlin:
- Basic Recursion: A straightforward recursive implementation.
- Tail Recursion: An optimized version using the
tailrec
modifier to prevent stack overflow. - Recursive Factorial with Input Validation: A robust implementation with input validation.
Each method has its advantages and can be chosen based on the requirements of the problem at hand. Understanding these different approaches helps in writing efficient and safe recursive functions in Kotlin.