English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to use recursive functions in Kotlin to find and display the factorial of a number.
The factorial of a positive number n is given by the following formula:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
The factorial of a negative number does not exist. The factorial of 0 is1.
In this example, you will learn to use recursion to find the factorial of a number. Visit this page to learn how to find the factorial of a number using a loop. Factorial.
fun main(args: Array<String>) { val num = 6 val factorial = multiplyNumbers(num) println("$num's factorial = $factorial") } fun multiplyNumbers(num: Int): Long { if (num >= 1) return num * multiplyNumbers(num - 1) else return 1 }
When running the program, the output is:
6 factorial = 720
Initially, call multiplyNumbers() from the main() function and pass6is passed as a parameter.
because6is greater than or equal to1, so6multiplied by the result of multiplyNumbers(), where5 (num -1). Because it is called from the same function, it is a recursive call.
In each recursive call, the value of the parameter num is reduced1, until num is less than1. When the value of num is less than1There is no recursive call when
Each recursive call returns to us:
6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720
The equivalent Java code is as follows:Java Program to Find Factorial Using Recursion