kotlin 尾递归
Given a number (num), we have to find the sum of the natural numbers from 1 to num.
给定一个数字( num ),我们必须找到从1到num的自然数之和。
Example:
例:
Input:
num = 5
Output:
1+2+3+4+5 = 15
该程序在Kotlin中使用递归找到1到N的自然数之和 (Program to find sum of natural numbers from 1 to N using recursion in Kotlin)
package com.includehelp.basic
import java.util.*
//function to calculate sum of natural number using recursion
fun addSum(number:Int):Int{
return if (number > 0) number + addSum(number - 1) else 0
}
//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 num: Int = scanner.nextInt()
//Call function to find out sum of all numbers up to given number
var sum= addSum(num)
//Print Sum
println("Sum of All Natural Numbers up to num are : $sum")
}
Output
输出量
Run 1:
Enter Number : 99
Sum of All Natural Numbers up to 99 are : 4950
---
Run 2:
Enter Number : 999
Sum of All Natural Numbers up to 999 are : 499500
翻译自: https://www.includehelp.com/kotlin/find-sum-of-natural-numbers-from-1-to-n-using-recursion.aspx
kotlin 尾递归