To find the factorial of a number, you can use a loop to multiply the number by each integer less than it until you reach 1. For example, to find the factorial of 5, you would perform the following calculation:
5! = 5 x 4 x 3 x 2 x 1 = 120
here’s an example Kotlin code to calculate the factorial of a number:
fun factorial(n: Int): Int {
var result = 1
for (i in 2..n) {
result *= i
}
return result
}
fun main() {
val n = 5
val fact = factorial(n)
println("The factorial of $n is $fact")
}
In this code, we define a function factorial
that takes an integer parameter n
and returns the factorial of n
. We initialize the result
variable to 1, and then loop from 2 to n
, multiplying result
by each integer in the range. Finally, we return result
as the output.
The time complexity of the factorial function is O(n), where n is the input number. This is because the algorithm iterates over each integer from 1 to n, performing a constant amount of work (i.e., multiplying by the current integer) at each step.
The space complexity of the factorial function is O(1), because the algorithm uses only a fixed amount of memory to store the result of the calculation (i.e., the variable holding the result) and the loop counter (i.e., the variable holding the current integer being multiplied). No additional memory is required as the input size grows larger.