English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin程序使用递归查找最大公因数

Comprehensive Collection of Kotlin Examples

在此程序中,您将学习使用Kotlin中的递归函数查找GCD(最大公因数)或HCF(最大公约数)。

该程序采用两个正整数,并使用递归计算GCD

访问此页面以了解如何使用循环来计算GCD

示例:使用递归的两个数字的最大公约数(GCD)

fun main(args: Array<String>) {
    val n1 = 366
    val n2 = 60
    val hcf = hcf(n1, n2)
    println("$n1和$n2的最大公因数等于$hcf.
}
fun hcf(n1: Int, n2: Int): Int {
    if (n2 != 0)
        return hcf(n2, n1 % n2)
    else
        return n1
}

When running this program, the output is:

366 and 6The greatest common divisor of 0 is 6.

 in the above program, the recursive function is called until n2is 0. Finally, n1is the Greatest Common Divisor (GCD) or Highest Common Factor (HCF) of the given two numbers.

Execution Steps
No.Recursive Calln1n2n1 % n2
1hcf(366,60)366606
2hcf(60,6)6060
3hcf(6,0)60--

The following is the equivalent Java code:Java Program to Find GCD Using Recursion

Comprehensive Collection of Kotlin Examples