Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tail Call Optimization #95

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 15 additions & 5 deletions src/main/kotlin/math/Factorial.kt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package mathematics
package math

import java.security.InvalidParameterException

Expand All @@ -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)
}
}
10 changes: 9 additions & 1 deletion src/test/kotlin/math/FactorialTest.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package mathematics
package math

import math.getFactorial
import org.junit.Test
import java.security.InvalidParameterException

Expand All @@ -25,4 +26,11 @@ class FactorialTest {
assert(getFactorial(input) == expectedFactorial)
}

@Test
fun testFactorialOfHighValue() {
val input = 20000L
val expectedFactorial = 0L
assert(getFactorial(input) == expectedFactorial)
}

}