Write a Kotlin Program to Find GCD of two Numbers

As a Kotlin programmer, finding the GCD of two numbers is a basic arithmetic operation that you should be able to perform.

The GCD or Greatest Common Divisor is the largest number that divides both given numbers. It is an important concept in mathematics and is used in many algorithms.

To find the GCD of two numbers in Kotlin, we can use the Euclidean algorithm.

This algorithm uses the fact that the GCD of two numbers does not change if the larger number is replaced by its difference with the smaller number.

Here is a Kotlin program that finds the GCD of two numbers using the Euclidean algorithm:

fun main() {
    val num1 = 24
    val num2 = 36
    var gcd: Int
    
    // Find the smaller number
    val smaller = if (num1 < num2) num1 else num2
    
    // Iterate from 1 to the smaller number
    for (i in 1..smaller) {
        // If the number is divisible by both num1 and num2, update gcd
        if (num1 % i == 0 && num2 % i == 0) {
            gcd = i
        }
    }
    
    // Print the GCD
    println("GCD of $num1 and $num2 is $gcd")
}

In this program, we first initialize the two numbers num1 and num2. We then find the smaller of the two numbers using the if statement.

We then use a for loop to iterate from 1 to the smaller number.

Inside the loop, we check if the current number is divisible by both num1 and num2. If it is, we update the gcd variable with the current number.

Finally, we print the GCD using the println function.

This program will output:

GCD of 24 and 36 is 12

The output is correct since 12 is the largest number that divides both 24 and 36.

In conclusion, finding the GCD of two numbers using the Euclidean algorithm is a basic arithmetic operation in Kotlin.

It is important for many algorithms and is a useful skill for any Kotlin programmer to have.