English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
在此程序中,您将学习使用Kotlin中的递归函数查找GCD(最大公因数)或HCF(最大公约数)。
该程序采用两个正整数,并使用递归计算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.
No. | Recursive Call | n1 | n2 | n1 % n2 |
---|---|---|---|---|
1 | hcf(366,60) | 366 | 60 | 6 |
2 | hcf(60,6) | 60 | 6 | 0 |
3 | hcf(6,0) | 6 | 0 | -- |
The following is the equivalent Java code:Java Program to Find GCD Using Recursion