Dado un número N , la tarea es encontrar la suma de la siguiente serie hasta N términos.
Ejemplos:
Entrada: N = 2
Salida: 3
1 + 2 = 3
Entrada: N = 5
Salida: 701
1 + 2 + 9 + 64 + 625 = 701
Enfoque: De la serie dada, encuentre la fórmula para el N-ésimo término:
1st term = 1 = 11-1 2nd term = 2 = 22-1 3rd term = 9 = 33-1 4th term = 64 = 44-1 . . Nth term = NN - 1
Por lo tanto:
Enésimo término de la serie
Luego itere sobre los números en el rango [1, N] para encontrar todos los términos usando la fórmula anterior y calcule su suma.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the sum of series void printSeriesSum(int N) { long long sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += pow(i, i - 1); } // Print the sum cout << sum << endl; } // Driver Code int main() { int N = 5; printSeriesSum(N); return 0; }
Java
// Java program for the above approach class GFG{ // Function to find the sum of series static void printSeriesSum(int N) { long sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += Math.pow(i, i - 1); } // Print the sum System.out.print(sum +"\n"); } // Driver Code public static void main(String[] args) { int N = 5; printSeriesSum(N); } } // This code is contributed by Princi Singh
Python3
# Python3 program for the above approach # Function to find the summ of series def printSeriessumm(N): summ = 0 for i in range(1,N+1): # Generate the ith term and # add it to the summ summ += pow(i, i - 1) # Print the summ print(summ) # Driver Code N = 5 printSeriessumm(N) # This code is contributed by shubhamsingh10
C#
// C# program for the above approach using System; class GFG{ // Function to find the sum of series static void printSeriesSum(int N) { double sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += Math.Pow(i, i - 1); } // Print the sum Console.Write(sum +"\n"); } // Driver Code public static void Main(String[] args) { int N = 5; printSeriesSum(N); } } // This code is contributed by PrinciRaj1992
Javascript
<script> // javascript program for the above approach // Function to find the sum of series function printSeriesSum( N) { let sum = 0; for (let i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += Math.pow(i, i - 1); } // Print the sum document.write(sum); } // Driver Code let N = 5; printSeriesSum(N); // This code is contributed by todaysgaurav </script>
Producción:
701
Complejidad de tiempo: O(N * log N)
Espacio Auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por shivanisinghss2110 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA