Skip to content

Commit

Permalink
Add GCD and LCM
Browse files Browse the repository at this point in the history
  • Loading branch information
kylecorry31 committed Jun 29, 2024
1 parent 0b29079 commit d55569c
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/main/kotlin/com/kylecorry/sol/math/SolMath.kt
Original file line number Diff line number Diff line change
Expand Up @@ -460,4 +460,35 @@ object SolMath {
}
}

fun greatestCommonDivisor(a: Long, b: Long): Long {
val maxIterations = 1000
var currentA = a
var currentB = b
var iterations = 0
while (currentB != 0L && iterations < maxIterations) {
val temp = currentB
currentB = currentA % currentB
currentA = temp
iterations++
}
return currentA
}

fun greatestCommonDivisor(a: Int, b: Int): Int {
return greatestCommonDivisor(a.toLong(), b.toLong()).toInt()
}

fun leastCommonMultiple(a: Long, b: Long): Long {
if (a == 0L || b == 0L) {
return 0
}
return abs(a) * (abs(b) / greatestCommonDivisor(a, b))
}

fun leastCommonMultiple(a: Int, b: Int): Int {
return leastCommonMultiple(a.toLong(), b.toLong()).toInt()
}



}
32 changes: 32 additions & 0 deletions src/test/kotlin/com/kylecorry/sol/math/SolMathTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,38 @@ class SolMathTest {
assertEquals(expected, actual)
}

@ParameterizedTest
@CsvSource(
"1, 1, 1",
"100, 200, 100",
"200, 100, 100",
"0, 0, 0",
"0, 1, 1",
"1, 0, 1",
"-1, 1, 1",
"400, 600, 200",
)
fun greatestCommonDivisor(a: Int, b: Int, expected: Int) {
val actual = SolMath.greatestCommonDivisor(a, b)
assertEquals(expected, actual)
}

@ParameterizedTest
@CsvSource(
"1, 1, 1",
"100, 200, 200",
"200, 100, 200",
"0, 0, 0",
"0, 1, 0",
"1, 0, 0",
"-1, 1, 1",
"400, 600, 1200",
)
fun leastCommonMultiple(a: Int, b: Int, expected: Int) {
val actual = SolMath.leastCommonMultiple(a, b)
assertEquals(expected, actual)
}

companion object {

@JvmStatic
Expand Down

0 comments on commit d55569c

Please sign in to comment.