Dado un entero n , la tarea es encontrar la suma de la serie 1 1 + 2 2 + 3 3 + ….. + n n usando recursividad.
Ejemplos:
Entrada: n = 2
Salida: 5
1 1 + 2 2 = 1 + 4 = 5
Entrada: n = 3
Salida: 32
1 1 + 2 2 + 3 3 = 1 + 4 + 27 = 32
Enfoque: a partir de n , comience a agregar todos los términos de la serie uno por uno con el valor de n disminuyendo en 1 en cada llamada recursiva hasta el valor de n = 1 para el cual devuelve 1 como 1 1 = 1 .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> 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
<?php // PHP implementation of the approach // Recursive function to return // the sum of the given series function sum($n) { // 1^1 = 1 if ($n == 1) return 1; else // Recursive call return (pow($n, $n) + sum($n - 1)); } // Driver code $n = 2; echo(sum($n)); // This code is contributed // by Code_Mech ?>
Javascript
<script> // Javascript implementation of the approach // Recursive function to return // the sum of the given series function sum(n) { // 1^1 = 1 if (n == 1) return 1; else // Recursive call return (Math.pow(n, n) + sum(n - 1)); } // Driver code var n = 2; document.write(sum(n)); // This code is contributed by rutvik_56. </script>
Producción:
5