Anonymous Kotlin function: Calculate a factorial
Write an anonymous Kotlin function to calculate the factorial of a number.
Pre-Knowledge (Before You Start!)
Before solving this exercise, you should be familiar with the following concepts:
- Factorial: A factorial of a number is the product of all positive integers less than or equal to the number. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.
- Recursion: Recursion is when a function calls itself to solve smaller instances of the same problem. In this case, the factorial function calls itself with a reduced value of the number.
- Base Case: In recursive functions, the base case prevents infinite recursion. Here, the base case is when the number is less than or equal to 1, returning 1.
- Function Syntax: You should understand how to define and call functions in Kotlin, including passing parameters and returning values.
Hints (Try Before Looking at the Solution!)
Here are some hints to help you solve the problem:
- Hint 1: Define a function that takes a number as an argument and returns the factorial.
- Hint 2: Use recursion inside the function by calling the function itself with a decremented value of the number.
- Hint 3: Use a base case to return 1 when the number is less than or equal to 1.
- Hint 4: Multiply the number by the result of the recursive call for n-1.
Sample Solution:
Kotlin Code:
fun main() {
val number = 5
fun factorial(n: Int): Int {
return if (n <= 1) {
1
} else {
n * factorial(n - 1)
}
}
val result = factorial(number)
println("Factorial of $number is $result")
}
Sample Output:
Factorial of 5 is 120
Explanation:
In the above exercise -
The function "factorial()" takes an integer n as input and calculates the factorial using recursion.
Inside the "factorial()" function, we check if n is less than or equal to 1, and if so, we return 1. Otherwise, we calculate the factorial by multiplying n with the factorial of n - 1.
Kotlin Editor:
Previous: Check palindrome string.
Next: Find maximum element in array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics