Factorial using a `for` loop in Kotlin
With Java programming experience, I started learning Kotlin today. I am playing around with the language and found I was stuck to find the factorial using a loop for
in kotlin. I managed to do this using a loop while
.
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 loop for
.
thank
source to share
This doesn't use a for loop, but as an addition, you can also make it 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 at the value at index 0.
We'll start with 2 instead, however 1 will be equivalent since multiplying by one will not change the result.
Edit 2: This edit is exactly what was just posted in holi java.
source to share
there is another expressive one using Range # fold and a function reference expression like:
fun factorial(n: Int) = (2..n).fold(1L, Long::times)
source to share
Factorial:
fun factorial(num : Long) : Long {
var factorial : Long = 1
for (i in 2..num) {
factorial *= i
}
println("Factorial of $num = $factorial")
}
Factorial using BigInteger variable:
fun factorial(num : Long) : Long {
var factorial = BigInteger.ONE
for (i in 2..num) {
factorial = factorial.multiply(BigInteger.valueOf(num))
}
println("Factorial of $num = $factorial")
}
source to share