给定一个整数n ,任务是使用递归找到序列1 1 + 2 2 + 3 3 +….. + n n的总和。
例子:
Input: n = 2
Output: 5
11 + 22 = 1 + 4 = 5
Input: n = 3
Output: 32
11 + 22 + 33 = 1 + 4 + 27 = 32
方法:从n开始,开始将系列的所有项逐个加法,其中n的值在每个递归调用中递减1 ,直到n = 1的值返回1等于1 1 = 1 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
#define ll long long int
// Recursive function to return
// the sum of the given series
ll sum(int n)
{
// 1^1 = 1
if (n == 1)
return 1;
else
// Recursive call
return ((ll)pow(n, n) + sum(n - 1));
}
// Driver code
int main()
{
int n = 2;
cout << sum(n);
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Recursive function to return
// the sum of the given series
static long sum(int n)
{
// 1^1 = 1
if (n == 1)
return 1;
else
// Recursive call
return ((long)Math.pow(n, n) + sum(n - 1));
}
// Driver code
public static void main(String args[])
{
int n = 2;
System.out.println(sum(n));
}
}
Python3
# Python3 implementation of the approach
# Recursive function to return
# the sum of the given series
def sum(n):
if n == 1:
return 1
else:
# Recursive call
return pow(n, n) + sum(n - 1)
# Driver code
n = 2
print(sum(n))
# This code is contributed
# by Shrikant13
C#
// C# implementation of the approach
using System;
class GFG {
// Recursive function to return
// the sum of the given series
static long sum(int n)
{
// 1^1 = 1
if (n == 1)
return 1;
else
// Recursive call
return ((long)Math.Pow(n, n) + sum(n - 1));
}
// Driver code
public static void Main()
{
int n = 2;
Console.Write(sum(n));
}
}
PHP
Javascript
输出:
5