简体   繁体   中英

Write a program to find sum of squares of all numbers given the following conditions?

Given two numbers n1 and n2 such that n2>n1, find sum of squares of all numbers from n1 to n2 (including n1 and n2).

My Approach:

I tried to solve the problem using a for loop iterated from n1 to n2 but I am getting wrong answer

Below is my function for the code:

public int computeSumofSquares (int n1, int n2) 
{
    int sum=0;
    if(n2>n1)
    {
        for(int i=n1;i<=n2;i++)
        {
            sum=((sum)+(n1*n1));
        }
    }
    return sum;
    //write your code here

}

For the Input

Parameters  Actual Output   Expected Output
'8' '10'    192             245

You are squaring n1 on every iteration. Instead you should square i . As a short form of sum=((sum)+(i*i)); you can write sum += i * i;

Change sum=((sum)+(n1*n1)); to sum=((sum)+(i*i)); as i is the value incrementing.

In your loop i changes every time but in your statement sum=((sum)+(n1*n1)); nothing changes and each time in your example you are summing 8^2 and the result would be 8*8 + 8*8 + 8*8 = 192.

As everybody said if you change n1 to i in that statement, something like sum=sum+i*i , then you will get the result you want.

As others have already stated, you were always using the lower bound of your interval n1 to calculate sum (instead of your loop variable i ).

For completeness, I'm posting a java8 solution:

int n1 = 8;
int n2 = 10;
int sumOfSquares = IntStream.rangeClosed(n1, n2).map(i -> i * i).sum();

System.out.println(sumOfSquares); // 245

Please check IntStream docs for further reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM