Dado un entero positivo, N . Encuentre la suma del primer N término de la serie-
1, (2+3), (4+5+6),….,hasta N términos
Ejemplos :
Entrada : N = 5
Salida : 120
Entrada : N = 1
Salida : 1
Enfoque : La secuencia se forma usando el siguiente patrón. Para cualquier valor N-
S norte = norte * (norte + 1) * (norte 2 + norte + 2) / 8
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to return sum of // N term of the series int findSum(int N) { return N * (N + 1) * (N * N + N + 2) / 8; } // Driver Code int main() { int N = 5; cout << findSum(N); }
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { // Function to return sum of // N term of the series static int findSum(int N) { return N * (N + 1) * (N * N + N + 2) / 8; } // Driver Code public static void main(String[] args) { int N = 5; System.out.println(findSum(N)); } } // This code is contributed by Potta Lokesh
Python3
# Python 3 program for the above approach # Function to return sum of # N term of the series def findSum(N): return N * (N + 1) * (N * N + N + 2) // 8 # Driver Code if __name__ == "__main__": # Value of N N = 5 print(findSum(N)) # This code is contributed by Abhishek Thakur.
C#
/*package whatever //do not write package name here */ using System; class GFG { // Function to return sum of // N term of the series static int findSum(int N) { return N * (N + 1) * (N * N + N + 2) / 8; } // Driver Code public static void Main() { int N = 5; Console.Write(findSum(N)); } } // This code is contributed by Saurabh Jaiswal
Javascript
// Javascript program to implement // the above approach // Function to return sum of // N term of the series function findSum(N) { return N * (N + 1) * (N * N + N + 2) / 8; } // Driver Code let N = 5 document.write(findSum(N)) // This code is contributed by saurabh_jaiswal.
Producción
120
Complejidad de Tiempo : O(1)
Espacio Auxiliar : O(1)
Publicación traducida automáticamente
Artículo escrito por akashjha2671 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA