SumSquareDifference.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /* The sum of the squares of the first ten natural numbers is,
  2. 12 + 22 + ... + 102 = 385
  3. The square of the sum of the first ten natural numbers is,
  4. (1 + 2 + ... + 10)2 = 552 = 3025
  5. Hence the difference between the sum of the squares of the first ten natural
  6. numbers and the square of the sum is 3025 − 385 = 2640.
  7. Find the difference between the sum of the squares of the first one hundred
  8. natural numbers and the square of the sum.
  9. */
  10. public class SumSquareDifference {
  11. private long sumSquareDifference;
  12. public SumSquareDifference() {
  13. this.sumSquareDifference = getSquareOfSums() - getSumOfSquares();
  14. }
  15. public long getDifference() {
  16. return this.sumSquareDifference;
  17. }
  18. private static int getSumOfSquares() {
  19. int sum = 0;
  20. for (int i = 1; i <= 100; i++) {
  21. double square = Math.pow(i, 2);
  22. sum += square;
  23. }
  24. return sum;
  25. }
  26. private static long getSquareOfSums() {
  27. long sum = 0;
  28. for (long i = 1; i <= 100; i++) {
  29. sum += i;
  30. }
  31. // To calculate and return the square of all the sums
  32. long square = sum * sum;
  33. return square;
  34. }
  35. }