- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find m-th summation of first n natural numbers in C++
In this problem, we are given two integers m and n. Our task is to Find m-th summation of the first n natural numbers.
Problem Description: we will find sum of sum of n natural numbers m times. The sum is given by the formula,
if (m > 1),
sum(n, m) = sum( sum(n, (m-1)), 1 )
if (m = 1)
sum(n, m) = sum(n, 1) = sum of n natural numbers
Let’s take an example to understand the problem,
Input: m = 4, n = 2
Output: 231
Explanation:
sum(2, 4) = sum ( sum(2, 3), 1 )
= sum ( sum ( sum (2, 2), 1) , 1 )
= sum ( sum ( sum (sum( 2, 1), 1) , 1 ), 1)
= sum ( sum ( sum (3, 1) , 1 ), 1)
= sum ( sum ( 6 , 1 ), 1)
= sum (21, 1)
= 231
Solution Approach −
A simple solution to the problem is by using two nested loops. The outer one will be for m values and the inner one will be for n values. We will update the value of n and we will calculate the sum of n natural number m times.
A more effective approach would be recursively calling the sum of n natural number m times updating the value with the previous sum each time recursion is made.
Algorithm:
Step 1: update sum value with sum = sum(n, m-1)* (sum(n, m-1)+1) / 2 if the sum value of m is greater than one.
Step 2: If the value of m = 1, return sum = n * (n+1) /2.
Step 3: return sum.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int calcSumN(int n, int m) { if (m == 1) return (n * (n + 1) / 2); return (calcSumN(n, m-1) * (calcSumN(n, m-1) + 1) / 2); } int main() { int n = 4; int m = 6; cout<<m<<"-th summation of first "<<n<<" natural numbers is "<<calcSumN(n, m); return 0; }
Output
6-th summation of first 4 natural numbers is 125230148