Dado un entero positivo N . La tarea es encontrar 1 2 + 2 2 + 3 2 + ….. + N 2 .
Ejemplos:
CPP
// CPP Program to find sum of square of first n natural numbers #include <bits/stdc++.h> using namespace std; // Return the sum of the square // of first n natural numbers int squaresum(int n) { // Iterate i from 1 and n // finding square of i and add to sum. int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum; } // Driven Program int main() { int n = 4; cout << squaresum(n) << endl; return 0; }
CPP
// CPP Program to find sum // of square of first n // natural numbers #include <bits/stdc++.h> using namespace std; // Return the sum of square of // first n natural numbers int squaresum(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driven Program int main() { int n = 4; cout << squaresum(n) << endl; return 0; }
CPP
// CPP Program to find sum of square of first // n natural numbers. This program avoids // overflow upto some extent for large value // of n. #include <bits/stdc++.h> using namespace std; // Return the sum of square of first n natural // numbers int squaresum(int n) { return (n * (n + 1) / 2) * (2 * n + 1) / 3; } // Driven Program int main() { int n = 4; cout << squaresum(n) << endl; return 0; }
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA