changed subtraction to modulo division for euclid algo, create a new factorial function with Kotlin optimization (tailrec), changed calculating middle variable in binary search
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -15,14 +15,14 @@ class Euclid {
|
||||
fun compute(num1: Int, num2: Int) : Int {
|
||||
var copyNum1 = num1
|
||||
var copyNum2 = num2
|
||||
while (copyNum1 != copyNum2) {
|
||||
while (copyNum1 != 0 && copyNum2 != 0) {
|
||||
if (copyNum1 > copyNum2) {
|
||||
copyNum1 -= copyNum2
|
||||
copyNum1 %= copyNum2
|
||||
} else {
|
||||
copyNum2 -= copyNum1
|
||||
copyNum2 %= copyNum1
|
||||
}
|
||||
}
|
||||
return copyNum1
|
||||
return copyNum1 + copyNum2
|
||||
}
|
||||
|
||||
}
|
||||
@ -39,4 +39,11 @@ class Factorial {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see <a href="https://kotlinlang.org/docs/functions.html#tail-recursive-functions">tailrec functions</a>
|
||||
*
|
||||
*/
|
||||
tailrec fun computeRecursiveWithKotlinOptimization(number: Int) : Int =
|
||||
if (number <= 1) 1 else number * computeRecursiveWithKotlinOptimization(number - 1)
|
||||
|
||||
}
|
||||
@ -22,7 +22,7 @@ class BinarySearch<T : Comparable<T>> : Search<T> {
|
||||
var left = -1
|
||||
var right = array.size
|
||||
while ((right - left) > 1) {
|
||||
val middle = (right + left) / 2
|
||||
val middle = left + (right - left) / 2
|
||||
if (element > array[middle]) {
|
||||
left = middle
|
||||
} else {
|
||||
|
||||
@ -25,6 +25,14 @@ internal class FactorialTest {
|
||||
assertEquals(720, factorial.computeRecursive(6))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun test_recursive_with_kotlin_optimization() {
|
||||
assertEquals(1, factorial.computeRecursiveWithKotlinOptimization(0))
|
||||
assertEquals(1, factorial.computeRecursiveWithKotlinOptimization(1))
|
||||
assertEquals(6, factorial.computeRecursiveWithKotlinOptimization(3))
|
||||
assertEquals(120, factorial.computeRecursiveWithKotlinOptimization(5))
|
||||
assertEquals(720, factorial.computeRecursiveWithKotlinOptimization(6))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user