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
Problem statement
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