Project Euler > Problem 6 > Sum square difference (Java Solution)

Problem:

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

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 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.


Solution:

25164150


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 6
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p006 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p006().run());
 }
 
 
 private static final int N = 100;
 
 
 public String run() {
  int sum = 0;
  int sum2 = 0;
  for (int i = 1; i <= N; i++) {
   sum += i;
   sum2 += i * i;
  }
  /* 
   * For the mathematically inclined:
   *   sum  = N(N + 1) / 2.
   *   sum2 = N(N + 1)(2N + 1) / 6.
   */
  return Integer.toString(sum * sum - sum2);
 }
 
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact