Skip to content

Commit b5fea3c

Browse files
Merge pull request TheAlgorithms#1461 from shellhub/master
Created Problem06 in Project Euler
2 parents 7536ef4 + a195c69 commit b5fea3c

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@
204204
* [Problem01](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem01.java)
205205
* [Problem02](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem02.java)
206206
* [Problem04](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem04.java)
207+
* [Problem06](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem06.java)
207208

208209
## Searches
209210
* [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/BinarySearch.java)

ProjectEuler/Problem06.java

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package ProjectEuler;
2+
3+
/**
4+
* The sum of the squares of the first ten natural numbers is,
5+
* 1^2 + 2^2 + ... + 10^2 = 385
6+
* The square of the sum of the first ten natural numbers is,
7+
* (1 + 2 + ... + 10)^2 = 552 = 3025
8+
* Hence the difference between the sum of the squares of the first ten natural
9+
* numbers and the square of the sum is 3025 − 385 = 2640.
10+
* Find the difference between the sum of the squares of the first N natural
11+
* numbers and the square of the sum.
12+
* <p>
13+
* link: https://projecteuler.net/problem=6
14+
*/
15+
public class Problem06 {
16+
public static void main(String[] args) {
17+
int[][] testNumbers = {
18+
{10, 2640},
19+
{15, 13160},
20+
{20, 41230},
21+
{50, 1582700}
22+
};
23+
24+
for (int[] testNumber : testNumbers) {
25+
assert solution1(testNumber[0]) == testNumber[1]
26+
&& solutions2(testNumber[0]) == testNumber[1];
27+
}
28+
}
29+
30+
private static int solution1(int n) {
31+
int sum1 = 0;
32+
int sum2 = 0;
33+
for (int i = 1; i <= n; ++i) {
34+
sum1 += i * i;
35+
sum2 += i;
36+
}
37+
return sum2 * sum2 - sum1;
38+
}
39+
40+
41+
private static int solutions2(int n) {
42+
int sumOfSquares = n * (n + 1) * (2 * n + 1) / 6;
43+
int squareOfSum = (int) Math.pow((n * (n + 1) / 2.0), 2);
44+
return squareOfSum - sumOfSquares;
45+
}
46+
}

0 commit comments

Comments
 (0)