Skip to content

Commit 0c1f5cd

Browse files
author
evitwilly
committed
changed subtraction to modulo division for euclid algo, create a new factorial function with Kotlin optimization (tailrec), changed calculating middle variable in binary search
1 parent ee301cd commit 0c1f5cd

File tree

9 files changed

+20
-5
lines changed

9 files changed

+20
-5
lines changed
Binary file not shown.
Binary file not shown.

.gradle/7.1/fileHashes/fileHashes.bin

0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
Binary file not shown.

src/main/kotlin/other/Euclid.kt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@ class Euclid {
1515
fun compute(num1: Int, num2: Int) : Int {
1616
var copyNum1 = num1
1717
var copyNum2 = num2
18-
while (copyNum1 != copyNum2) {
18+
while (copyNum1 != 0 && copyNum2 != 0) {
1919
if (copyNum1 > copyNum2) {
20-
copyNum1 -= copyNum2
20+
copyNum1 %= copyNum2
2121
} else {
22-
copyNum2 -= copyNum1
22+
copyNum2 %= copyNum1
2323
}
2424
}
25-
return copyNum1
25+
return copyNum1 + copyNum2
2626
}
2727

2828
}

src/main/kotlin/other/Factorial.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,11 @@ class Factorial {
3939
}
4040
}
4141

42+
/**
43+
* @see <a href="https://kotlinlang.org/docs/functions.html#tail-recursive-functions">tailrec functions</a>
44+
*
45+
*/
46+
tailrec fun computeRecursiveWithKotlinOptimization(number: Int) : Int =
47+
if (number <= 1) 1 else number * computeRecursiveWithKotlinOptimization(number - 1)
48+
4249
}

src/main/kotlin/search/BinarySearch.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class BinarySearch<T : Comparable<T>> : Search<T> {
2222
var left = -1
2323
var right = array.size
2424
while ((right - left) > 1) {
25-
val middle = (right + left) / 2
25+
val middle = left + (right - left) / 2
2626
if (element > array[middle]) {
2727
left = middle
2828
} else {

src/test/kotlin/other/FactorialTest.kt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ internal class FactorialTest {
2525
assertEquals(720, factorial.computeRecursive(6))
2626
}
2727

28+
@Test
29+
fun test_recursive_with_kotlin_optimization() {
30+
assertEquals(1, factorial.computeRecursiveWithKotlinOptimization(0))
31+
assertEquals(1, factorial.computeRecursiveWithKotlinOptimization(1))
32+
assertEquals(6, factorial.computeRecursiveWithKotlinOptimization(3))
33+
assertEquals(120, factorial.computeRecursiveWithKotlinOptimization(5))
34+
assertEquals(720, factorial.computeRecursiveWithKotlinOptimization(6))
35+
}
2836

2937

3038
}

0 commit comments

Comments
 (0)