w3resource

Kotlin Program: Find the GCD of two numbers

Kotlin Control Flow: Exercise-10 with Solution

Write a Kotlin program to find the GCD (Greatest Common Divisor) of two numbers.

Sample Solution:

Kotlin Code:

fun main() {
    val number1 = 28
    val number2 = 16

    val gcd = findGCD(number1, number2)

    println("GCD of $number1 and $number2: $gcd")
}

fun findGCD(number1: Int, number2: Int): Int {
    var num1 = number1
    var num2 = number2

    while (num2 != 0) {
        val temp = num2
        num2 = num1 % num2
        num1 = temp
    }

    return num1
}

Sample Output:

GCD of 28 and 16: 4

Explanation:

In the above exercise -

  • In "main()" function "number1" and "number2" variables represent the two numbers for which we want to find the GCD.
  • The "findGCD()" function takes the two numbers as arguments and calculates their GCD.
  • Inside the findGCD() function, we initialize variables "num1" and "num2" with the values of "number1" and "number2" respectively.
  • We use a while loop to repeatedly divide num1 by "num2" until "num2" becomes zero.
  • In each iteration, we store the value of "num2" in a temporary variable temp and update "num2" to the remainder of "num1" divided by num2.
  • We then updated "num1" to "temp".
  • This process continues until "num2" becomes zero, at which point "num1" will hold the GCD of the original "number1" and "number2".
  • Finally, we return the value of "num1", which is the GCD.

Kotlin Editor:


Previous: Count even and odd elements in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.