kotlin 尾递归_Kotlin程序使用递归找到1到N的自然数之和

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 尾递归

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值