kotlin 尾递归阶乘
Given a number, we have to find its factorial using recursion.
给定一个数字,我们必须使用递归来找到它的阶乘。
Example:
例:
Input:
5
Output:
120
在Kotlin中使用递归程序查找给定数字的阶乘 (Program to find factorial of a given number using recursion in Kotlin)
package com.includehelp.basic
import java.util.*
//function to calculate factorial using recursion
fun findFactorial(number:Int):Int{
return if (number > 1) number * findFactorial(number - 1) else 1
}
//Main Function entry Point of Program
fun main(args: Array<String>) {
//Input Stream
val scanner = Scanner(System.`in`)
//input integer number
print("Enter Number : ")
val number: Int = scanner.nextInt()
//Number should be Non Negative
if(number>=0){
//Call function to find out sum of all numbers up to given number
var sum= findFactorial(number)
//Print Sum
println("Factorial of $number is : $sum")
}
else{
System.err.println("Factorial of $number not Exist")
}
}
Output
输出量
Run 1:
Enter Number : 5
Factorial of 5 is : 120
---
Run 2:
Enter Number : 0
Factorial of 0 is : 1
---
Run 3:
Enter Number : -4
Factorial of -4 not Exist
---
Run 4:
Enter Number : 9
Factorial of 9 is : 362880
翻译自: https://www.includehelp.com/kotlin/find-factorial-of-a-given-number-using-recursion.aspx
kotlin 尾递归阶乘