FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/ProjectEuler/Problem06.java at master · loisoft/Java · GitHub
loisoft
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
ProjectEuler
/
Problem06.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
42 lines (38 loc) · 1.23 KB
Breadcrumbs
Java
/
ProjectEuler
/
Problem06.java
Copy path
File metadata and controls
42 lines (38 loc) · 1.23 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
;
}
}
Back
|
FazBrowse Home
|
New Git URL