Sum of the series 1^1 + 2^2 + 3^3 + ….. + n^n using recursion
Given an integer n, the task is to find the sum of the series 11 + 22 + 33 + ….. + nn using recursion.
Examples:
Input: n = 2
Output: 5
11 + 22 = 1 + 4 = 5
Input: n = 3
Output: 32
11 + 22 + 33 = 1 + 4 + 27 = 32
Approach: Starting from n, start adding all the terms of the series one by one with the value of n getting decremented by 1 in each recursive call until the value of n = 1 for which return 1 as 11 = 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll sum( int n)
{
if (n == 1)
return 1;
else
return ((ll) pow (n, n) + sum(n - 1));
}
int main()
{
int n = 2;
cout << sum(n);
return 0;
}
|
Java
class GFG {
static long sum( int n)
{
if (n == 1 )
return 1 ;
else
return (( long )Math.pow(n, n) + sum(n - 1 ));
}
public static void main(String args[])
{
int n = 2 ;
System.out.println(sum(n));
}
}
|
Python3
def sum (n):
if n = = 1 :
return 1
else :
return pow (n, n) + sum (n - 1 )
n = 2
print ( sum (n))
|
C#
using System;
class GFG {
static long sum( int n)
{
if (n == 1)
return 1;
else
return (( long )Math.Pow(n, n) + sum(n - 1));
}
public static void Main()
{
int n = 2;
Console.Write(sum(n));
}
}
|
PHP
<?php
function sum( $n )
{
if ( $n == 1)
return 1;
else
return (pow( $n , $n ) + sum( $n - 1));
}
$n = 2;
echo (sum( $n ));
?>
|
Javascript
<script>
function sum(n)
{
if (n == 1)
return 1;
else
return (Math.pow(n, n) + sum(n - 1));
}
var n = 2;
document.write(sum(n));
</script>
|
Time Complexity: O(nlogn), for using pow function for numbers 1 till N.
Auxiliary Space: O(n) for recursive stack space.
Last Updated :
22 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...