Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Created July 24, 2013 18:23
Show Gist options
  • Select an option

  • Save rfaisal/6073118 to your computer and use it in GitHub Desktop.

Select an option

Save rfaisal/6073118 to your computer and use it in GitHub Desktop.
Find the difference between the sum of the squares of the first n natural numbers and the square of the sum.
public class SumSquareDiff {
public static long calculate(int n){
int sum_of_sq=0;
int sum=0;
for(int i=1;i<=n;i++){
sum+=i;
sum_of_sq+=i*i;
}
return sum*sum-sum_of_sq;
}
}
public class SumSquareDiffTest {
@Test
public void testCalculate() {
assertEquals(2640, SumSquareDiff.calculate(10));
assertEquals(25164150, SumSquareDiff.calculate(100));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment