Q:

Kotlin program to find GCD/HCF of two numbers

belongs to collection: Kotlin Basic Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to convert temperature from Fahrenh... >>
<< Kotlin program to calculate and display student gr...