两个数之间范围内的平方和

Sum of squares in range between two numbers

我应该使用给定函数及其参数编写平方和公式。我可以添加变量,但我似乎做对了。我想出的公式只计算两个数字之间的总和(不是平方和)。

int sumOfSquares(int nLowerBound,
                 int nUpperBound) {
    // your code here
    int nSum;
    nSum = ( (nUpperBound * (nUpperBound + 1)) - (nLowerBound * (nLowerBound - 1)) ) / 2;
    
    return nSum;
}

计算总和的最简单方法是使用循环:

int sumOfSquares(int nLowerBound,
                 int nUpperBound) {
    // Initially set the sum as zero
    int nSum = 0; 

    for (int i=nLowerBound; i<=nUpperBound; i++) {
        // for each number between the bounds, add its square to the sum
        nSum = nSum + i*i; 
    }
    
    return nSum;
}

接受的答案推荐一个循环。但是这里不需要循环。

连续平方和有一个well-known公式:

公式为:

 0^2 + 1^2 + 2^2 + ... + n^2 == n*(n+1)*(2*n+1)/6. 

这是从0到n。我们可以通过从(从0到b的总和)中减去(从0到a-1的总和)来推导出从a到b的总和的公式。

int sumOfSquares(int nLowerBound,
                 int nUpperBound) {
    /* sum of squares from nLowerBound**2 to nUpperBound**2, included */
    int lowerSum = (nLowerBound-1) * nLowerBound * (2*nLowerBound-1) / 6;
    int upperSum = nUpperBound * (nUpperBound+1) * (2*nUpperBound+1) / 6;
    
    return upperSum - lowerSum;
}

可以这样:

int sumOfSquares(int nLowerBound,
             int nUpperBound) {

int nSum = 0; 

for (int i=nLowerBound; i<=nUpperBound; i++) {

    nSum = nSum + i*i; 
}

return nSum;

}