Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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
like image 508
Jason arora Avatar asked Oct 27 '15 14:10

Jason arora


1 Answers

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;

like image 136
kai Avatar answered Oct 12 '22 15:10

kai