Posted By

binaryadder on 10/16/11


Tagged


Versions (?)

Problem 6


 / Published in: Java
 

Project Euler Question 6:

"The sum of the squares of the first ten natural numbers is,

1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum."

Input: 1 100

Output: 25164150

  1. public class Prob6{
  2. public static void main(String[] argsv){
  3. int start = new Integer(argsv[0]).intValue();
  4. int end = new Integer(argsv[1]).intValue();
  5. System.out.println(difference(start, end));
  6. }
  7.  
  8. private static long difference(int start, int end){
  9. return squareOfSum(start, end) - sumOfSquares(start, end);
  10. }
  11.  
  12. private static long squareOfSum(int start, int end){
  13. long result = 0;
  14. while(start <= end){
  15. result += start;
  16. start++;
  17. }
  18. return result * result;
  19. }
  20.  
  21. // Interval [start, end]
  22. private static long sumOfSquares(int start, int end){
  23. long result = 0;
  24. while(start <= end){
  25. result += start * start;
  26. start++;
  27. }
  28. return result;
  29. }
  30. }

Report this snippet  

You need to login to post a comment.