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:

Input:
n = 4

Output:
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
Updated on: 2025-07-01T15:32:28+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements