Kotlin Program to Find G.C.D Using Recursion

This program takes two positive integers and calculates GCD using recursion.

Visit this page to learn how you can calculate the GCD using loops.

Example: GCD of Two Numbers using Recursion

fun main(args: Array<String>) {
    val n1 = 366
    val n2 = 60
    val hcf = hcf(n1, n2)

    println("G.C.D of $n1 and $n2 is $hcf.")
}

fun hcf(n1: Int, n2: Int): Int {
    if (n2 != 0)
        return hcf(n2, n1 % n2)
    else
        return n1
}

When you run the program, the output will be:

G.C.D of 366 and 60 is 6.

In the above program, the recursive function is called until n2 is 0. In the end, the value of n1 is the GCD or HCF of the given two numbers.

Execution Steps
No. Recursive call n1 n2 n1 % n2
1 hcf(366, 60) 366 60 6
2 hcf(60, 6) 60 6 0
Final hcf(6, 0) 6 0 -

Here's the equivalent Java code: Java Program to Find G.C.D. using recursion

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges