Problem 6 : Sum square difference
The sum of the squares of the first ten natural numbers is,
12 + 22 + … + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
1. 第6个问题:和平方之差
前十个自然数的平方之和是:
12 + 22 + … + 102 = 385
前十个自然数之和的平方是:
(1 + 2 + … + 10)2 = 552 = 3025
因此前十个自然数的和的平方与平方之和的差是: 3025 − 385 = 2640.
求前一百个自然数的和的平方与平方之和的差。
2. 求解分析
如果我们使用一个函数来计算前n个自然数的平方之和,另一个函数来计算前n个自然数的和的平方的话,就很容易得到两者的差了。
3. C++ 代码实现
类PE0006包含三个方法:getSumOfSquares(), getSquareOfSum()和getSumSquareDifference()。
函数getSumOfSquares()计算从1到n的平方之和。
函数getSquareOfSum()计算从1到n的和的平方。
函数getSumSquareDifference()计算从1到n的和的平方与平方之和的差。
C++ 代码
#include <iostream>
#include <cassert>
using namespace std;
class PE0006
{
private:
int getSumOfSquares(int n);
int getSquareOfSum(int n);
public:
int getSumSquareDifference(int n);
};
int PE0006::getSumOfSquares(int n)
{
// sumOfSquares = 1^2 + 2^2 + 3^2 + ... + n^2
int sumOfSquares = 0;
for(int i=1; i<=n; i++)
{
sumOfSquares += i*i;
}
return sumOfSquares;
}
int PE0006::getSquareOfSum(int n)
{
// squareOfSum = (1 + 2 + 3 + ... + n)^2
int sum = n*(n+1)/2;
int squareOfSum = sum*sum;
return squareOfSum ;
}
int PE0006::getSumSquareDifference(int n)
{
return (getSquareOfSum(n) - getSumOfSquares(n));
}
int main()
{
PE0006 pe0006;
assert(2640 == pe0006.getSumSquareDifference(10));
cout << "The difference between the sum of the squares of 1..100 and the ";
cout << "square of the sum is " << pe0006.getSumSquareDifference(100) << endl;
return 0;
}
4. Python 代码实现
Python实现方法跟C++一样,也包含三个函数。
Python 代码
def getSumOfSqures(n):
"""compute sum of squares from 1 to n^n """
sumOfSquares = 0
for i in range(1, n+1):
sumOfSquares += i*i;
return sumOfSquares
def getSqureOfSum(n):
"""compute square of sum from 1 to n """
sum = (1+n)*n/2
squareOfSum = sum*sum
return squareOfSum
def getSumSquareDifference(n):
return int(getSqureOfSum(n) - getSumOfSqures(n))
def main():
assert 2640 == getSumSquareDifference(10)
print("The difference between the sum of the squares of the first one ")
print("hundred natural numbers and the square of the sum is ", end='')
print(getSumSquareDifference(100), ".")
if __name__ == '__main__':
main()