ADVERTISEMENT
ADVERTISEMENT

Home » Kotlin » Kotlin programs » Kotlin basic programs

Kotlin program to find GCD/HCF of two numbers using recursion

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

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

Example:

    Input:
    456, 56

    Output:
    8

Program to find GCD/HCF of two numbers using recursion in Kotlin

package com.includehelp.basic

import java.util.*

//function calculate HCF using Recursion
fun findHCF(num1: Int,num2: Int):Int{
    return if(num2!=0) findHCF(num2,num1%num2) else num1
}


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

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


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

    var hcf=findHCF(first,second)

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

Output

Run 1:
Enter First Number  : 456
Enter First Number  : 56
GCD or HCF of 456 and 56 is : 8
-------
Run 2:
Enter First Number  : 500
Enter First Number  : 240
GCD or HCF of 500 and 240 is : 20
-------
Run 3:
Enter First Number  : 2345
Enter First Number  : 145
GCD or HCF of 2345 and 145 is : 5
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.