With experience of java programming, I started learning Kotlin today. I am playing with the language and found me stuck to find a factorial using for
loop in kotlin. I managed to do this using while
loop.
import java.util.Scanner
fun main(args: Array<String>){
val reader=Scanner(System.`in`)
val x: Int = reader.nextInt()
println(factorial(x))
}
fun factorial(a: Int): Int{
var ans=1
var i: Int = a
while(i>1){
ans*=i
i--
}
return ans
}
Please help me to do this using a for
loop.
Thanks
Well, the simplest one that comes to mind:
fun factorial(num: Int): Long {
var result = 1L
for (i in 2..num) result *= i
return result
}
This doesn't use a for loop, but just as an addition you can also make this shorter, more functional and Kotlin-like using reduce
:
fun factorial(num: Int) = (1..num).reduce(Int::times)
Or:
fun factorial(num: Int) = (1..num).reduce { a, b -> a * b }
This is the simplest I can think of.
Edit: This is equivalent to
fun factorial(num: Int) = (2..num).fold(1, Int::times)
as reduce
is practically a fold
starting from the value at index 0.
We start with 2 instead, however 1 would be equivalent as multiplying by one doesn't change the result.
Edit 2: this edit is exactly what holi-java just posted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With