[SOLVED] Sum of squares in range between two numbers

Issue

I’m supposed to write a formula for the sum of squares using the given function and its parameters. I am allowed to add variables but I can’t seem to get it right. The formula I came up with only computes the summation between the two numbers (not the sum of the squares).

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

Solution

The simplest way to compute the sum is to use a loop:

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;
}

Answered By – Aziz

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.