From ecdf57be47e44e74a3c05c82bb07a32df302cdc1 Mon Sep 17 00:00:00 2001 From: Davi Dante Date: Sat, 19 Nov 2022 17:56:25 -0300 Subject: [PATCH 1/2] feat: creating tail-recursive call for factorial algorithm --- .idea/misc.xml | 2 +- src/main/kotlin/math/Factorial.kt | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) 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..95457b0 100644 --- a/src/main/kotlin/math/Factorial.kt +++ b/src/main/kotlin/math/Factorial.kt @@ -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 From 414504dff91cd0639a59a6214e650b45365efed4 Mon Sep 17 00:00:00 2001 From: Davi Dante Date: Sat, 19 Nov 2022 17:58:33 -0300 Subject: [PATCH 2/2] feat: renaming packages and creating test for new tail-recursive function --- src/main/kotlin/math/Factorial.kt | 2 +- src/test/kotlin/math/FactorialTest.kt | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/kotlin/math/Factorial.kt b/src/main/kotlin/math/Factorial.kt index 95457b0..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 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