The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
Example 1: Find Factorial of a number using for loop
fun main(args: Array<String>) {
val num = 10
var factorial: Long = 1
for (i in 1..num) {
// factorial = factorial * i;
factorial *= i.toLong()
}
println("Factorial of $num = $factorial")
}
When you run the program, the output will be:
Factorial of 10 = 3628800
In this program, we've used for loop to loop through all numbers between 1 and the given number num (10), and the product of each number till num is stored in a variable factorial.
Unlike Java, in Kotlin, you can use ranges (1..num
) and in operator to loop through numbers between 1 to num.
Also, we've used long instead of int to store large results of factorial.
However, it's still not big enough to store the value of bigger numbers (say 100). For results that cannot be stored in a long variable, we use BigInteger
variable declared in java.math
library.
Here's the equivalent Java code: Java Program to Find Factorial of a Number.
Example 2: Find Factorial of a number using BigInteger
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(i.toLong()))
}
println("Factorial of $num = $factorial")
}
When you run the program, the output will be:
Factorial of 30 = 265252859812191058636308480000000
Here, instead of long
, we use BigInteger
variable factorial.
Since, *
cannot be used with BigInteger
, we instead use multiply()
for the product. Also, num should be casted to BigInteger
for multiplication.
Likewise, we can also use a while loop to solve this problem.
Example 3: Find Factorial of a number using while loop
fun main(args: Array<String>) {
val num = 5
var i = 1
var factorial: Long = 1
while (i <= num) {
factorial *= i.toLong()
i++
}
println("Factorial of $num = $factorial")
}
When you run the program, the output will be:
Factorial of 5 = 120
In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.
Though both programs are technically correct, it is better to use for loop in this case. It's because the number of iteration (upto num) is known.
Visit this page to learn to find factorial of a number using recursion.