Sum of natural numbers using recursion
Last Updated :
17 Feb, 2023
Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum().
Examples :
Input : 3
Output : 6
Explanation : 1 + 2 + 3 = 6
Input : 5
Output : 15
Explanation : 1 + 2 + 3 + 4 + 5 = 15
Below is code to find the sum of natural numbers up to n using recursion :
C++
#include <iostream>
using namespace std;
int recurSum( int n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
int main()
{
int n = 5;
cout << recurSum(n);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class GFG
{
public static int recurSum( int n)
{
if (n <= 1 )
return n;
return n + recurSum(n - 1 );
}
public static void main(String args[])
{
int n = 5 ;
System.out.println(recurSum(n));
}
}
|
Python
def recurSum(n):
if n < = 1 :
return n
return n + recurSum(n - 1 )
n = 5
print (recurSum(n))
|
C#
using System;
class GFG
{
public static int recurSum( int n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
public static void Main()
{
int n = 5;
Console.WriteLine(recurSum(n));
}
}
|
PHP
<?php
function recurSum( $n )
{
if ( $n <= 1)
return $n ;
return $n + recurSum( $n - 1);
}
$n = 5;
echo (recurSum( $n ));
?>
|
Javascript
<script>
function recurSum(n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
let n = 5;
document.write(recurSum(n));
</script>
|
Output :
15
Time complexity : O(n)
Auxiliary space : O(n)
To solve this question , iterative approach is the best approach because it takes constant or O(1) auxiliary space and the time complexity will be same O(n).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...