VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-mth-summation-first-n-natural-numbers/

⇱ Find m-th summation of first n natural numbers. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find m-th summation of first n natural numbers.

Last Updated : 13 Apr, 2023

m-th summation of first n natural numbers is defined as following.
 

If m > 1
 SUM(n, m) = SUM(SUM(n, m - 1), 1)
Else 
 SUM(n, 1) = Sum of first n natural numbers.


We are given m and n, we need to find SUM(n, m).
Examples: 
 

Input : n = 4, m = 1 
Output : SUM(4, 1) = 10
Explanation : 1 + 2 + 3 + 4 = 10

Input : n = 3, m = 2 
Output : SUM(3, 2) = 21
Explanation : SUM(3, 2) 
 = SUM(SUM(3, 1), 1) 
 = SUM(6, 1) 
 = 21


 


Naive Approach : We can solve this problem using two nested loop, where outer loop iterate for m and inner loop iterate for n. After completion of a single outer iteration, we should update n as whole of inner loop got executed and value of n must be changed then. Time complexity should be O(n*m). 
 

for (int i = 1;i <= m;i++)
{
 sum = 0;
 for (int j = 1;j <= n;j++)
 sum += j;
 n = sum; // update n
}


Efficient Approach : 
We can use direct formula for sum of first n numbers to reduce time. 
We can also use recursion. In this approach m = 1 will be our base condition and for any intermediate step SUM(n, m), we will call SUM (SUM(n, m-1), 1) and for a single step SUM(n, 1) = n * (n + 1) / 2 will be used. This will reduce our time complexity to O(m). 
 

int SUM (int n, int m)
{
 if (m == 1)
 return (n * (n + 1) / 2);
 int sum = SUM(n, m-1);
 return (sum * (sum + 1) / 2);
}


Below is the implementation of above idea :
 

Output: 
 

SUM(5, 3): 7260

Space complexity :- O(M)


 

Comment
Article Tags: