Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of the series 1^1 + 2^2 + 3^3 + ... + n^n using recursion in C++
In this article, we are given a mathematical series (1^1 + 2^2 + 3^3 + ? + n^n) defined by a number n which defines the nth terms of the series. This series can be represented mathematically as: $$ \displaystyle\sum\limits_{k=1}^n k^k $$
The above series does not have any specific mathematical name but is generally referred to as the power tower series. Below is an example of the power tower series up to n.
Example
The following example calculates the sum of the given series 1^1 + 2^2 + 3^3 + ? + n^n where value of n is 4:
<strong>Input:</strong> n = 4 <strong>Output:</strong> 1 + 4 + 27 + 256 = 288
Calculating Sum of Series Using Recursion
To solve the given series 1^1 + 2^2 + 3^3 + ..... + n^n, we have used a recursive function. The recursive function calculates the sum of self-power (n^n) starting from n till it reaches 1. It recursively calculates the self-power of elements and adds the self-power of its previous values and then we return the sum of the series.
Example
Here is an example of calculating the sum of the series up to 7 using recursion:
#include <iostream>
#include <cmath>
using namespace std;
long long powerTower(int n)
{
if (n == 1)
return 1;
int sum = pow(n, n) + powerTower(n - 1);
return sum;
}
int main()
{
int n = 7;
cout << "Sum of series 1^1 + 2^2 + ... + " << n
<< "^" << n << " : " << powerTower(n) << endl;
return 0;
}
The output of the above code is as follows:
Sum of series 1^1 + 2^2 + ... + 7^7 : 873612
