English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to find the GCD of two numbers

Kotlin Comprehensive Examples

In this program, you will learn how to find the GCD of two numbers in Kotlin. This is done by using a while loop with the help of if-else statements.

The HCF or GCD of two integers is the largest integer that can be exactly divided into the two numbers (without a remainder).

Example1: Use the while loop to find the GCD of two numbers

fun main(args: Array<String>) {
    val n =1 = 81
    val n =2 = 153
    var gcd = 1
    var i = 1
    while (i <= n1 && i <= n2) {
        //Check if i is a factor of the two integers
        if (n1 % i == 0 && n2 % i == 0)
            gcd = i
        ++i
    }
    println("$n1and $n2The greatest common divisor is $gcd)
}

The output when running the program is:

81 and 153 The greatest common divisor is 9 9

Here, the two numbers whose greatest common divisor will be found are stored in n1and n2In this case

Then, execute the for loop until i is less than n1and n2Iterate1Find the largest common factor by taking all numbers down to the smallest of the two numbers.

If n1and n2If all numbers can be divided by i, set gcd to the number. Continue this process until the largest number (GCD) is found, which will be n1and n2Divide evenly without a remainder.

Unlike Java, you cannot use a conditional for loop to solve this problem. Here is the equivalent Java code:Java program to find the GCD of two numbers.

The following is a better method to find the GCD in Kotlin:

Example2: Find the GCD of two numbers (a better alternative)

fun main(args: Array<String>) {
    var n1 = 81
    var n2 = 153
    while (n1 != n2) {
        if (n1 > n2)
            n1 -= n2
        else
            n2 -= n1
    }
    println("G.C.D = $n"1")
}

The output when running the program is:

G.C.D = 9

This is a better method to find the GCD. In this method, subtract the smaller integer from the larger integer, and then assign the result to the variable that holds the larger integer. This process continues until n1and n2Equal.

The above two programs can only work as expected when the user inputs a positive integer. This is a modified version of the second example that can find the GCD of positive and negative integers.

Example3:GCD of Positive and Negative Numbers

fun main(args: Array<String>) {
    var n1 = 81
    var n2 = -153
    //Always be a positive number
    n1 = if (n1 > 0) n1 else -n1
    n2 = if (n2 > 0) n2 else -n2
    while (n1 != n2) {
        if (n1 > n2)
            n1 -= n2
        else
            n2 -= n1
    }
    println("G.C.D = $n"1")
}

The output when running the program is:

G.C.D = 9

Kotlin Comprehensive Examples