Sling Academy
Home/Kotlin/Finding the Greatest Common Divisor (GCD) in Kotlin

Finding the Greatest Common Divisor (GCD) in Kotlin

Last updated: November 30, 2024

The Greatest Common Divisor (GCD) of two numbers is the largest positive integer that divides both numbers without leaving a remainder. It is an important concept in number theory and has several applications in mathematics and computer science.

Methods to Calculate GCD in Kotlin

In Kotlin, there are various ways to calculate the GCD. We will explore these methods step by step:

Using the Euclidean Algorithm

The Euclidean Algorithm is a simple and efficient method to compute the GCD of two numbers. It is based on the principle that the GCD of two numbers does not change if the larger number is replaced by its difference with the smaller number.


fun gcdUsingEuclideanAlgorithm(a: Int, b: Int): Int {
    var num1 = a
    var num2 = b
    while (num2 != 0) {
        val temp = num2
        num2 = num1 % num2
        num1 = temp
    }
    return num1
}

fun main() {
    val number1 = 56
    val number2 = 98
    println("GCD of $number1 and $number2 is: ${gcdUsingEuclideanAlgorithm(number1, number2)}")
}

This function employs a while loop to repetitively apply the Euclidean step num2 = num1 % num2 and swaps the values until num2 becomes zero. At this point, num1 holds the GCD.

Using Kotlin's Built-in Function

Kotlin provides a built-in extension function to compute the GCD using its BigInteger class. This can be utilized particularly when working with very large numbers.


import java.math.BigInteger

fun gcdUsingBigInteger(a: Int, b: Int): BigInteger {
    val bigInt1 = BigInteger.valueOf(a.toLong())
    val bigInt2 = BigInteger.valueOf(b.toLong())
    return bigInt1.gcd(bigInt2)
}

fun main() {
    val number1 = 56
    val number2 = 98
    println("GCD of $number1 and $number2 using BigInteger is: ${gcdUsingBigInteger(number1, number2)}")
}

Here, we use Kotlin's BigInteger class to call the gcd() method, which simplifies the computation.

Using Recursion

Recursion is another common approach to find the GCD. The Euclidean algorithm can also be implemented recursively.


fun gcdUsingRecursion(a: Int, b: Int): Int {
    return if (b == 0) a else gcdUsingRecursion(b, a % b)
}

fun main() {
    val number1 = 56
    val number2 = 98
    println("GCD of $number1 and $number2 using recursion is: ${gcdUsingRecursion(number1, number2)}")
}

This version calls the gcd function recursively until the base case is met: when b becomes 0, a is the GCD.

Conclusion

Kotlin provides versatile ways to calculate the GCD using iterative, built-in, or recursive methods. Each has its use-case, from ease of understanding using loops, utilizing efficient built-in functions, to exploring recursion concepts. Whichever method you choose, Kotlin makes it elegantly straightforward to find the GCD of any two integers.

Next Article: Working with Prime Numbers in Kotlin

Previous Article: How to Use Modulo for Cyclic Arithmetic in Kotlin

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin