diff --git a/.idea/misc.xml b/.idea/misc.xml index 4b49563..c23634d 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,7 +1,7 @@ - + \ No newline at end of file diff --git a/src/main/kotlin/math/Factorial.kt b/src/main/kotlin/math/Factorial.kt index e33be00..6058816 100644 --- a/src/main/kotlin/math/Factorial.kt +++ b/src/main/kotlin/math/Factorial.kt @@ -1,4 +1,4 @@ -package mathematics +package math import java.security.InvalidParameterException @@ -10,9 +10,19 @@ import java.security.InvalidParameterException fun getFactorial(number: Long): Long { if (number < 0L) { throw InvalidParameterException("The number of which to calculate the factorial must be greater or equal to zero.") - } else return when (number) { - 0L -> 1 - 1L -> number - else -> number * getFactorial(number - 1) + } else return getFactorialOptimized(number, 1) +} + +/** + * Calculates the factorial using tail recursion to optimize code. + * If the number is too high, the tail recursion returns 0. + * @param number The number of which to calculate the factorial. + * @param accumulator The accumulator of the factorial value + * @return The factorial of the number passed as parameter. + */ +private tailrec fun getFactorialOptimized(number: Long, accumulator: Long): Long { + return when (number) { + 0L -> accumulator + else -> getFactorialOptimized(number - 1, number * accumulator) } } \ No newline at end of file diff --git a/src/test/kotlin/math/FactorialTest.kt b/src/test/kotlin/math/FactorialTest.kt index 7706828..4c6c92e 100644 --- a/src/test/kotlin/math/FactorialTest.kt +++ b/src/test/kotlin/math/FactorialTest.kt @@ -1,5 +1,6 @@ -package mathematics +package math +import math.getFactorial import org.junit.Test import java.security.InvalidParameterException @@ -25,4 +26,11 @@ class FactorialTest { assert(getFactorial(input) == expectedFactorial) } + @Test + fun testFactorialOfHighValue() { + val input = 20000L + val expectedFactorial = 0L + assert(getFactorial(input) == expectedFactorial) + } + } \ No newline at end of file