给定正整数N。任务是找到1 2 + 2 2 + 3 2 +….. + N 2 。
例子:
Input : N = 4
Output : 30
12 + 22 + 32 + 42
= 1 + 4 + 9 + 16
= 30
Iput : N = 5
Output : 55
方法1:O(N)的想法是运行一个从1到n的循环,对于每个i,1 <= i <= n,求和2。
// CPP Program to find sum of square of first n natural numbers
#include
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;
}
输出:
30
方法2:O(1)
证明:
We know,
(k + 1)3 = k3 + 3 * k2 + 3 * k + 1
We can write the above identity for k from 1 to n:
23 = 13 + 3 * 12 + 3 * 1 + 1 ......... (1)
33 = 23 + 3 * 22 + 3 * 2 + 1 ......... (2)
43 = 33 + 3 * 32 + 3 * 3 + 1 ......... (3)
53 = 43 + 3 * 42 + 3 * 4 + 1 ......... (4)
...
n3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 ......... (n - 1)
(n + 1)3 = n3 + 3 * n2 + 3 * n + 1 ......... (n)
Putting equation (n - 1) in equation n,
(n + 1)3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 + 3 * n2 + 3 * n + 1
= (n - 1)3 + 3 * (n2 + (n - 1)2) + 3 * ( n + (n - 1) ) + 1 + 1
By putting all equation, we get
(n + 1)3 = 13 + 3 * Σ k2 + 3 * Σ k + Σ 1
n3 + 3 * n2 + 3 * n + 1 = 1 + 3 * Σ k2 + 3 * (n * (n + 1))/2 + n
n3 + 3 * n2 + 3 * n = 3 * Σ k2 + 3 * (n * (n + 1))/2 + n
n3 + 3 * n2 + 2 * n - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n2 + 3 * n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n + 1) * (n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n + 1) * (n + 2 - 3/2) = 3 * Σ k2
n * (n + 1) * (2 * n + 1)/2 = 3 * Σ k2
n * (n + 1) * (2 * n + 1)/6 = Σ k2
// CPP Program to find sum
// of square of first n
// natural numbers
#include
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;
}
输出:
30
避免过早溢出:
对于大n,(n *(n + 1)*(2 * n + 1))的值将溢出。我们可以使用n *(n + 1)必须被2整除的事实在一定程度上避免溢出。
// 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
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;
}
输出:
30
有关更多详细信息,请参阅关于第n个自然数的平方和的完整文章!
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。