Move History

Rooted by: Factorial
Fork Selected
  • Description

    Using the reduce methods

    Code
    fun fact(n: Int): Int {
        return (1..n).reduce { acc, i -> acc * i }
    }
    
    Test Cases
    // You can test using JUnit or KotlinTest. JUnit is shown below
    // TODO: replace this example test with your own, this is just here to demonstrate usage.
    
    // TODO: replace with whatever your package is called
    
    
    import kotlin.test.assertEquals
    import org.junit.Test
    
    class FactTest {
      @Test
      fun testFact() {
        assertEquals(2, fact(2))
        assertEquals(720, fact(6))
        assertEquals(3628800, fact(10))
      }
    }
    
  • Code
    • fun fact(n: Int): Int {
    • return (1..n).fold(1) { acc, i -> acc * i }
    • return (1..n).reduce { acc, i -> acc * i }
    • }