Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@
* [Problem01](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem01.java)
* [Problem02](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem02.java)
* [Problem04](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem04.java)
* [Problem06](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem06.java)

## Searches
* [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/BinarySearch.java)
Expand Down
46 changes: 46 additions & 0 deletions ProjectEuler/Problem06.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package ProjectEuler;

/**
* 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 = 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 N natural
* numbers and the square of the sum.
* <p>
* link: https://projecteuler.net/problem=6
*/
public class Problem06 {
public static void main(String[] args) {
int[][] testNumbers = {
{10, 2640},
{15, 13160},
{20, 41230},
{50, 1582700}
};

for (int[] testNumber : testNumbers) {
assert solution1(testNumber[0]) == testNumber[1]
&& solutions2(testNumber[0]) == testNumber[1];
}
}

private static int solution1(int n) {
int sum1 = 0;
int sum2 = 0;
for (int i = 1; i <= n; ++i) {
sum1 += i * i;
sum2 += i;
}
return sum2 * sum2 - sum1;
}


private static int solutions2(int n) {
int sumOfSquares = n * (n + 1) * (2 * n + 1) / 6;
int squareOfSum = (int) Math.pow((n * (n + 1) / 2.0), 2);
return squareOfSum - sumOfSquares;
}
}