Open In App

Sum of natural numbers using recursion

Last Updated : 17 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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++




// 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>


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).



Previous Article
Next Article

Similar Reads

Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order
Given two integers N and K, the task is to find the Kth element in the permutation of first N natural numbers arranged such that all the even numbers appear before the odd numbers in increasing order. Examples : Input: N = 10, K = 3 Output: 6Explanation:The required permutation is {2, 4, 6, 8, 10, 1, 3, 5, 7, 9}.The 3rd number in the permutation is
9 min read
Minimize sum of numbers required to convert an array into a permutation of first N natural numbers
Given an array A[] of size N, the task is to find the minimum sum of numbers required to be added to array elements to convert the array into a permutation of 1 to N. If the array can not be converted to desired permutation, print -1. Examples: Input: A[] = {1, 1, 1, 1, 1}Output: 10Explanation: Increment A[1] by 1, A[2] by 2, A[3] by 3, A[4] by 4,
5 min read
Sum of sum of all subsets of a set formed by first N natural numbers
Given N, and ff(N) = f(1) + f(2) + ...... + f(N), where f(k) is the sum of all subsets of a set formed by first k natural numbers. The task is to find ff(N) modulo 1000000007. Examples: Input: 2 Output: 7 f(1) + f(2) f(1) = 1 = 1 f(2) = 1 + 2 + {1 + 2} = 6 Input: 3 Output: 31 f(1) + f(2) + f(3) f(1) = 1 = 1 f(2) = 1 + 2 + {1 + 2} = 6 f(3) = 1 + 2 +
11 min read
Difference between Sum of Cubes and Sum of First N Natural Numbers
Given an integer N, find the absolute difference between sum of the cubes of first N natural numbers and the sum of first N natural numbers. Input: N = 3 Output: 30 Sum of first three numbers is 3 + 2 + 1 = 6 Sum of Cube of first three numbers is = 1 + 8 + 27 = 36 Absolute difference = 36 - 6 = 30 Input: N = 5 Output: 210 Approach: The sum of the c
4 min read
Sum of sum-series of first N Natural numbers
Given a natural number n, find the sum of the sum-series of the first N natural number. Sum-Series: is sum of first N natural numbers, i.e, sum-series of 5 is 15 ( 1 + 2 + 3 + 4 + 5 ). Natural number123456Sum of natural number (sum-series)136101521Sum of sum-series1410203556 Example: Input: N = 5 Output: 35 Explanation: Sum of sum-series of {1, 2,
6 min read
Sum of series formed by difference between product and sum of N natural numbers
Given a natural number N, the task is to find the sum of the series up to Nth term where the ith term denotes the difference between the product of first i natural numbers and sum of first i natural numbers, i.e., { 1 - 1 } + { (1 * 2) - (2 + 1) } + { (1 * 2 * 3) - (3 + 2 + 1) } + { (1 * 2 * 3 * 4) - (4 + 3 + 2 + 1) } + ......... Examples: Input: 2
10 min read
Check if a given number can be expressed as pair-sum of sum of first X natural numbers
Given an integer N, the task is to check if N is the sum of a pair of integers which can be expressed as the sum of first X natural numbers, where X can be any positive integer. If satisfies the required condition. Print “YES”. Otherwise, print “NO”. Examples: Input: N = 25Output: YESExplanation:=&gt; 10 + 15 = 25Since 10 and 15 are the sum of firs
10 min read
Difference between sum of the squares of first n natural numbers and square of sum
Given an integer n, find the absolute difference between sum of the squares of first n natural numbers and square of sum of first n natural numbers.Examples : Input : n = 3Output : 22Sum of first three numbers is 3 + 2 + 1 = 6Square of the sum = 36Sum of squares of first three is 9 + 4 + 1 = 14Absolute difference = 36 - 14 = 22Input : n = 10Output
7 min read
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Given two integers N and K, the task is to find the total number of ways of representing N as the sum of positive integers in the range [1, K], where each integer can be chosen multiple times. Examples: Input: N = 8, K = 2Output: 5Explanation: All possible ways of representing N as sum of positive integers less than or equal to K are: {1, 1, 1, 1,
9 min read
Fill the missing numbers in the array of N natural numbers such that arr[i] not equal to i
Given an unsorted array arr[] consisting of N natural numbers and the missing numbers as 0 such that arr[i] ? i, the task is to find and fill these missing numbers without changing the initial order. Please note that the array can contain numbers from 1 to N only once. Examples: Input: arr[] = {7, 4, 0, 3, 0, 5, 1} Output: 7 4 6 3 2 5 1 Explanation
9 min read
Bitwise XOR of first N natural numbers that are product of two distinct Prime Numbers
Given a positive integer N, the task is to calculate the Bitwise XOR of first N numbers which are a product of exactly two distinct prime numbers. Examples: Input: N = 20Output: 7Explanation: The numbers from the range [1, 20] which are a product of exactly two distinct prime numbers are {6, 10, 12, 14, 15, 18, 20}.Bitwise XOR of these numbers = 6
8 min read
Count total set bits in first N Natural Numbers (all numbers from 1 to N)
Given a positive integer N, the task is to count the total number of set bits in binary representation of all natural numbers from 1 to N. Examples: Input: N = 3Output: 4Explanation: Numbers from 1 to 3: {1, 2, 3}Binary Representation of 1: 01 -&gt; Set bits = 1Binary Representation of 2: 10 -&gt; Set bits = 1Binary Representation of 3: 11 -&gt; Se
15+ min read
Product of 2 Numbers using Recursion
Given two numbers x and y find the product using recursion. Examples : Input : x = 5, y = 2 Output : 10 Input : x = 100, y = 5 Output : 500 Method 1) If x is less than y, swap the two variables value 2) Recursively find y times the sum of x 3) If any of them become zero, return 0 C/C++ Code // C++ Program to find Product // of 2 Numbers using Recur
4 min read
Product of 2 numbers using recursion | Set 2
Given two numbers N and M. The task is to find the product of the 2 numbers using recursion.Note: The numbers can be both positive or negative. Examples: Input : N = 5 , M = 3 Output : 15 Input : N = 5 , M = -3 Output : -15 Input : N = -5 , M = 3 Output : -15 Input : N = -5 , M = -3 Output:15 A recursive solution to the above problem for only posit
8 min read
Find HCF of two numbers without using recursion or Euclidean algorithm
Given two integer x and y, the task is to find the HCF of the numbers without using recursion or Euclidean method. Examples: Input: x = 16, y = 32 Output: 16 Input: x = 12, y = 15 Output: 3 Approach: HCF of two numbers is the greatest number which can divide both the numbers. If the smaller of the two numbers can divide the larger number then the H
6 min read
Print even and odd numbers in a given range using recursion
Given two integers L and R, the task is to print all the even and odd numbers from L to R using recursion. Examples: Input: L = 1, R = 10Output: Even numbers: 2 4 6 8 10Odd numbers: 1 3 5 7 9 Input: L = 10, R = 25 Output: Even numbers:10 12 14 16 18 20 22 24 Odd numbers:11 13 15 17 19 21 23 25 Approach: Follow the steps below to solve the problem u
6 min read
C Program to find LCM of two numbers using Recursion
Given two integers N and M, the task is to find their LCM using recursion. Examples: Input: N = 2, M = 4Output: 4Explanation: LCM of 2, 4 is 4. Input: N = 3, M = 5Output: 15Explanation: LCM of 3, 5 is 15. Approach: The idea is to use the basic elementary method of finding LCM of two numbers. Follow the steps below to solve the problem: Define a rec
3 min read
Print numbers 1 to N using Indirect recursion
Given a number N, we need to print numbers from 1 to N with out direct recursion, loops, labels. Basically we need to insert in above code snippet so that it can be able to print numbers from 1 to N? C/C++ Code #include &lt;stdio.h&gt; #define N 20; int main() { // Your code goes Here. } Examples : Input : 10 Output : 1 2 3 4 5 6 7 8 9 10 Input : 5
5 min read
Add Two Numbers represented as Linked List using Recursion
Given two numbers represented as two lists, the task is to return the sum of two lists using recursion. Examples: Input: num1 = 4 -&gt; 5, num2 = 3 -&gt; 4 -&gt; 5Output: 3 -&gt; 9 -&gt; 0 Explanation: Sum of 45 and 345 is 390. Input: num1 = 1 -&gt; 2 -&gt; 3, num2 = 9 -&gt; 9 -&gt; 9Output: 1 -&gt; 1 -&gt; 2 -&gt; 2 Explanation: Sum of 123 and 999
13 min read
Program to find sum of first n natural numbers
Given a number n, find the sum of the first natural numbers. Examples : Input: n = 3 Output: 6 Explanation: Note that 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : Note that 1 + 2 + 3 + 4 + 5 = 15Program to Find the Sum of First N Natural Numbers A simple solution is to do the following. 1) Initialize : sum = 0 2) Run a loop from x = 1 to n and
10 min read
Sum of squares of first n natural numbers
Given n, find sum of squares of first n natural numbers. Examples : Input : n = 2 Output : 5 Explanation: 1^2+2^2 = 5 Input : n = 8 Output : 204 Explanation : 1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 = 204 Naive approach : A naive approach will be to run a loop from 1 to n and sum up all the squares. C/C++ Code // C program to calculate // 1^2
10 min read
Sum of fourth powers of the first n natural numbers
Write a program to find the sum of fourth powers of the first n natural numbers 14 + 24 + 34 + 44 + …….+ n4 till n-th term.Examples : Input : 4 Output : 354 14 + 24 + 34 + 44 = 354 Input : 6 Output : 2275 14 + 24 + 34 + 44+ 54+ 64 = 2275 Naive Approach :- Simple finding the fourth powers of the first n natural numbers is iterate a loop from 1 to n
7 min read
Sum of fourth power of first n even natural numbers
Write a program to find the sum of fourth power of first n even natural numbers. 24 + 44 + 64 + 84 + 104 +.........+2n4 Examples: Input: 3Output: 156824 +44 +64 = 1568 Input: 6Output: 3640024 + 44 + 64 + 84 + 104 + 124 Naive Approach :- In this Simple finding the fourth powers of the first n even natural numbers is iterate a loop from 1 to n time.
7 min read
Sum of fourth powers of first n odd natural numbers
Write a program to find sum of fourth power of first n odd natural numbers. 14 + 34 + 54 + 74 + 94 + 114 .............+(2n-1)4. Examples: Input : 3 Output : 707 14 +34 +54 = 707 Input : 6 Output : 24310 14 + 34 + 54 + 74 + 94 + 114 Naive Approach: - In this Simple finding the fourth power of the first n odd natural numbers is to iterate a loop from
8 min read
Sum of cubes of even and odd natural numbers
We know that sum of cubes of first n natural numbers is = (n(n+1)/2)2. Sum of cube of first n even natural numbers 23 + 43 + 63 + ......... + (2n)3 Even Sum = 23 + 43 + 63 + .... + (2n)3 if we multiply by 23 then = 23 x (13 + 23 + 33 + .... + (n)3) = 23 + 43 + 63 + ......... + (2n)3 = 23 (n(n+1)/2)2 = 8(n(n+1))2/4 = 2(n(n+1))2 Example : Sum of cube
2 min read
Sum of range in a series of first odd then even natural numbers
The sequence first consists of all the odd numbers starting from 1 to n and then remaining even numbers starting 2 up to n. Let's suppose we have n as 1000. Then the sequence becomes 1 3 5 7....999 2 4 6....1000We are given a range (L, R), we need to find sum of numbers of this sequence in a given range. Note: Here the range is given as (L, R) L an
7 min read
Sum of first N natural numbers by taking powers of 2 as negative number
Given a number N ( maybe up to 10^9 ). The task is to find the sum of first N natural number taking powers of 2 as a negative number.Examples: Input: N = 4 Output: -4 - 1 - 2 + 3 - 4 = -4 1, 2, and 4 are the powers of two. Input: N = 5 Output: 1 Approach: An efficient solution is to store the powers of two in an array and then store presum of this
8 min read
Find sum of N-th group of Natural Numbers
Given a series of natural numbers divided into groups as: (1, 2), (3, 4, 5, 6), (7, 8, 9, 10, 11, 12), (13, 14, 15, 16, 17, 18, 19, 20)..... and so on. Given a number N, the task is to find the sum of the numbers in the Nth group. Examples: Input : N = 3 Output : 57 Numbers in 3rd group are: 7, 8, 9, 10, 11, 12 Input : N = 10 Output : 2010 The firs
3 min read
Sum of all natural numbers in range L to R
Given a range L and R, the task is to find the sum of all natural numbers in range L to R. Examples: Input: L = 2, R = 5 Output: 14 2 + 3 + 4 + 5 = 14 Input: L = 10, R = 20 Output: 165 A naive approach is to traverse from L to R and add all the elements one by one to get the sum.An efficient approach is to use the formula for the sum of first N nat
4 min read
Practice Tags :