Q:

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

belongs to collection: Kotlin Recursion Programs

0

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

Example:

    Input:
    456, 56

    Output:
    8

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

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

total answers (1)

Kotlin program for Decimal to Binary conversion us... >>
<< Kotlin program to find factorial of a given number...