Home » Kotlin » Kotlin programs » Kotlin basic programs

Kotlin program to find GCD/HCF of two numbers

Kotlin | GCD/HCF of two numbers: Here, we are going to learn how to find GCD/HCF of two given numbers in Kotlin programming language?
Submitted by IncludeHelp, on April 25, 2020

What is HCF/GCD?

HCF stands for "Highest Common Factor" and GCD stands of "Greatest Common Divisor", both terms are the same. The greatest/highest common devisors number which divides each of the two or more numbers, i.e. HCF/CGD is the highest number which divides each number.

Given two numbers, we have to find GCD/HCF.

Example:

    Input:
    first = 50
    second = 78

    Output: 
    HCF/GCD = 2

Program to find GCD/HCF of two numbers in Kotlin

package com.includehelp.basic

import java.util.*

//Main Function entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val scanner = Scanner(System.`in`)

    //input First integer
    print("Enter First Number  : ")
    val first: Int = scanner.nextInt()


    //input Second integer
    print("Enter Second Number  : ")
    val second: Int = scanner.nextInt()

    var gcd=1
    var i=1

    //Running Loop to find out GCD
    while (i<=first && i<=second){
        //check if i is factor of both numbers
        if(first%i==0 && second%i==0){
            gcd=i
        }
        i++
    }

    //print GCD or HCF
    println("GCD or HCF of $first and $second is : $gcd")
}

Output

Run 1:
Enter First Number  : 50
Enter First Number  : 78
GCD or HCF of 50 and 78 is : 2
-------
Run 2:
Enter First Number  : 500
Enter First Number  : 240
GCD or HCF of 500 and 240 is : 20
-------
Run 3:
Enter First Number  : 243
Enter First Number  : 81
GCD or HCF of 243 and 81 is : 81



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.