Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorial using `for` loop in Kotlin

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

like image 605
Anmol Gautam Avatar asked Jul 19 '17 15:07

Anmol Gautam


2 Answers

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
}
like image 56
Alexander Romanov Avatar answered Sep 20 '22 17:09

Alexander Romanov


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.

like image 24
Salem Avatar answered Sep 19 '22 17:09

Salem