使用递归的自然数和

图片[1]-使用递归的自然数和-yiteyi-C++库

null

给定一个数n,求第一个数的和 N 自然数。为了计算和,我们将使用递归函数recur_sum()。 例如:

Input : 3Output : 6Explanation : 1 + 2 + 3 = 6Input : 5Output : 15Explanation : 1 + 2 + 3 + 4 + 5 = 15

下面是使用递归求n以下自然数之和的代码:

C++

// C++ program to find the
// sum of natural numbers up
// to n using recursion
#include <iostream>
using namespace std;
// Returns sum of first
// n natural numbers
int recurSum( int n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
// Driver code
int main()
{
int n = 5;
cout << recurSum(n);
return 0;
}


JAVA

// Java program to find the
// sum of natural numbers up
// to n using recursion
import java.util.*;
import java.lang.*;
class GFG
{
// Returns sum of first
// n natural numbers
public static int recurSum( int n)
{
if (n <= 1 )
return n;
return n + recurSum(n - 1 );
}
// Driver code
public static void main(String args[])
{
int n = 5 ;
System.out.println(recurSum(n));
}
}
// This code is contributed by Sachin Bisht


python

# Python code to find sum
# of natural numbers upto
# n using recursion
# Returns sum of first
# n natural numbers
def recurSum(n):
if n < = 1 :
return n
return n + recurSum(n - 1 )
# Driver code
n = 5
print (recurSum(n))


C#

// C# program to find the
// sum of natural numbers
// up to n using recursion
using System;
class GFG
{
// Returns sum of first
// n natural numbers
public static int recurSum( int n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
// Driver code
public static void Main()
{
int n = 5;
Console.WriteLine(recurSum(n));
}
}
// This code is contributed by vt_m


PHP

<?php
// PHP program to find the
// sum of natural numbers
// up to n using recursion
// Returns sum of first
// n natural numbers
function recurSum( $n )
{
if ( $n <= 1)
return $n ;
return $n + recurSum( $n - 1);
}
// Driver code
$n = 5;
echo (recurSum( $n ));
// This code is contributed by Ajit.
?>


Javascript

<script>
// JavaScript program to find the
// sum of natural numbers
// up to n using recursion
// Returns sum of first
// n natural numbers
function recurSum(n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
// Driver code
let n = 5;
document.write(recurSum(n));
// This code is contributed by mohan
</script>


输出:

15 

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享