English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn how to use for and while loops to find the factorial of a number in Kotlin. You will also learn to use range to solve this problem.
The factorial of a positive number is given by the formula n:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
fun main(args: Array<String>) { val num = 10 var factorial: Long = 1 for (i in 1.. num) { // factorial = factorial * i; factorial *= i.toLong() } println("$num's factorial = $factorial") }
The output when running the program is:
10 's factorial = 3628800
In this program, we use a loop to iterate over1to the given number num(10) to get all the numbers between
Unlike Java, in Kotlin, you can userange(1.. num) andin operator in1looping through the numbers between
Similarly, we use long instead of int to store the factorial result of larger numbers.
However, it may still not be enough to store the value of larger numbers (such as1...10For results that cannot be stored in a long variable, we use the BigInteger variable declared in the java.math library.
This is the equivalent Java code:Java program to find the factorial of a number
import java.math.BigInteger fun main(args: Array<String>) { val num = 30 var factorial = BigInteger.ONE for (i in 1.. num) { // factorial = factorial * i; factorial = factorial.multiply(BigInteger.valueOf(num.toLong())) } println("$num's factorial = $factorial") }
The output when running the program is:
30's factorial = 205891132094649000000000000000000000000000000
Here, we use the factorial of the BigInteger variable instead of long.
Since * The operator cannot be used with BigInteger, so we use multiply() for the product. Additionally, num should be converted to BigInteger for multiplication.
Similarly, we can also use a while loop to solve this problem.
fun main(args: Array<String>) { val num = 5 var i = 1 var factorial: Long = 1 while (i <= num) { factorial *= i.toLong() i++ } println("$num! = $factorial") }
The output when running the program is:
5 Factorial = 120
In the above program, unlike the for loop, we must increase the value of i inside the loop body.
Although both programs are technically correct, it is best to use a for loop in this case. This is because the number of iterations (up to num) is known.