Kotlin Program to Find Factorial of a Number
for (i in 1..n) result *= i to multiply all numbers from 1 to n.Examples
How to Think About It
Algorithm
Code
fun main() {
val n = 5
var factorial = 1L
for (i in 1..n) {
factorial *= i
}
println("Factorial of $n is $factorial")
}Dry Run
Let's trace the factorial calculation for n=5 through the code
Initialize
n = 5, factorial = 1
Multiply by 1
factorial = 1 * 1 = 1
Multiply by 2
factorial = 1 * 2 = 2
Multiply by 3
factorial = 2 * 3 = 6
Multiply by 4
factorial = 6 * 4 = 24
Multiply by 5
factorial = 24 * 5 = 120
| i | factorial |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Start with 1
We start the factorial result at 1 because multiplying by 1 does not change the value and it is the identity for multiplication.
Step 2: Multiply step by step
We multiply the result by each number from 1 up to n to accumulate the product that defines factorial.
Step 3: Handle zero case
If the input is 0, factorial is 1 by definition, so we return 1 immediately without looping.
Alternative Approaches
fun factorial(n: Int): Long = if (n == 0) 1 else n * factorial(n - 1) fun main() { val n = 5 println("Factorial of $n is ${factorial(n)}") }
fun main() {
val n = 5
val factorial = (1..n).fold(1L) { acc, i -> acc * i }
println("Factorial of $n is $factorial")
}Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n once, so the time grows linearly with n, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The iterative loop is fastest and safest for large n compared to recursion, which can cause stack overflow.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | Large inputs, safe and fast |
| Recursive function | O(n) | O(n) | Elegant code, small inputs |
| Fold function | O(n) | O(1) | Concise functional style |