Dado un número N, la tarea es encontrar la suma del primer número N de la serie:
-1, 2, 11, 26, 47, 74, …..
Ejemplos:
Input: N = 3 Output: 12 Explanation: Sum = (N * (N + 1) * (2 * N - 5) + 4 * N) / 2 = (3 * (3 + 1) * (2 * 3 - 5) + 4 * 3) / 2 = 12 Input: N = 9 Output: 603
Enfoque:
El término N de la serie dada se puede generalizar como: El
término N de la serie
A continuación se muestra la implementación del enfoque anterior:
C++
// CPP program to find SUM // upto N-th term of the series: // -1, 2, 11, 26, 47, 74, ..... #include <iostream> using namespace std; // calculate Nth term of series int findSum(int N) { return (N * (N + 1) * (2 * N - 5) + 4 * N) / 2; } // Driver Function int main() { // Get the value of N int N = 3; // Get the sum of the series cout << findSum(N) << endl; return 0; }
Java
// Java program to find SUM // upto N-th term of the series: // -1, 2, 11, 26, 47, 74, ..... import java.util.*; class solution { static int findSum(int N) { return (N * (N + 1) * (2 * N - 5) + 4 * N) / 2; } //driver function public static void main(String arr[]) { // Get the value of N int N = 3; // Get the sum of the series System.out.println(findSum(N)); } } //THis code is contributed by //Surendra_Gangwar
Python3
# Python3 program to find sum # upto N-th term of the series: # -1, 2, 11, 26, 47, 74, ..... # calculate Nth term of series def findSum(N): return ((N * (N + 1) * (2 * N - 5) + 4 * N) / 2) #Driver Function if __name__=='__main__': #Get the value of N N = 3 #Get the sum of the series print(findSum(N)) #this code is contributed by Shashank_Sharma
C#
// C# program to find SUM // upto N-th term of the series: // -1, 2, 11, 26, 47, 74, ..... using System; class GFG { static int findSum(int N) { return (N * (N + 1) * (2 * N - 5) + 4 * N) / 2; } // Driver Code static public void Main () { // Get the value of N int N = 3; // Get the sum of the series Console.Write(findSum(N)); } } // This code is contributed by Raj
PHP
<?php // PHP program to find SUM // upto N-th term of the series: // -1, 2, 11, 26, 47, 74, ..... // calculate Nth term of series function findSum($N) { return ($N * ($N + 1) * (2 * $N - 5) + 4 * $N) / 2; } // Driver Code // Get the value of N $N = 3; // Get the sum of the series echo findSum($N) . "\n"; // This code is contributed // by Akanksha Rai(Abby_akku) ?>
Javascript
<script> // javascript program to find SUM // upto N-th term of the series: // -1, 2, 11, 26, 47, 74, ..... function findSum(N) { return (N * (N + 1) * (2 * N - 5) + 4 * N) / 2; } //driver function // Get the value of N var N = 3; // Get the sum of the series document.write(findSum(N)); // This code is contributed by 29AjayKumar </script>
Producción:
12
Complejidad de tiempo: O(1)