Kotlin Program to Find GCD of two Numbers

Kotlin Server Side ProgrammingProgramming

In this article, we will understand how to find the GCD of two numbers in Kotlin. Greatest Common Divisor (GCD) of two numbers is the largest number that divides both.

Below is a demonstration of the same

Suppose our input is

Value 1 : 18
Value 2 : 24

The desired output would be

GCD of the two numbers: 6

Algorithm

  • Step 1 − Start

  • Step 2 − Declare three integers: input1, input2 and myResult

  • Step 3 − Define the integer

  • Step 4 − Check that the number divides both (input1 and input2) numbers completely or not. If divides completely store it in a variable.

  • Step 5 − Display the ‘i’ value as GCD of the two numbers

  • Step 6 − Stop

Example 1

In this example, we will find the GCD of two numbers in Kotlin using while loop. First, declare and set the two inputs for which we will find the GCD later

var input1 = 18
var input2 = 24

Also, set a variable for Result

var myResult = 1

Now, use the while loop and get the GCD

var i = 1 while (i <= input1 && i <= input2) { if (input1 % i == 0 && input2 % i == 0) myResult = i ++i }

Let us now see the complete example

fun main() { var input1 = 18 var input2 = 24 var myResult = 1 println("The input values are defined as $input1 and $input2") var i = 1 while (i <= input1 && i <= input2) { if (input1 % i == 0 && input2 % i == 0) myResult = i ++i } println("The result is $myResult") }

Output

The input values are defined as 18 and 24
The result is 6

Example 2

In this example, we will find the GCD of two numbers in Kotlin −

fun main() { val input1 = 18 val input2 = 24 println("The input values are defined as $input1 and $input2") getGCD(input1, input2) } fun getGCD(input1: Int, input2: Int){ var myResult = 1 var i = 1 while (i <= input1 && i >= input2) { if (input1 % i == 0 && input2 % i == 0) myResult = i ++i } println("The result is $myResult") }

Output

The input values are defined as 18 and 24
The result is 6

Example 3

In this example, we will find the GCD of two numbers in Kotlin using while loop but with an alternative way −

fun main() { var input1 = 18 var input2 = 24 println("The input values are defined as $input1 and $input2") while (input1 != input2) { if (input1 > input2) input1 -= input2 else input2 -= input1 } println("The result is $input1") }

Output

The input values are defined as 18 and 24
The result is 6
raja
Updated on 13-Oct-2022 12:39:09

Advertisements