File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments