forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp058.java
More file actions
41 lines (34 loc) · 1.07 KB
/
p058.java
File metadata and controls
41 lines (34 loc) · 1.07 KB
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
/*
* Solution to Project Euler problem 58
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p058 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p058().run());
}
/*
* From the diagram, let's observe the four corners of an n * n square (where n is odd).
* It's not hard to convince yourself that:
* - The bottom right corner always has the value n^2.
* Working clockwise (backwards):
* - The bottom left corner has the value n^2 - (n - 1).
* - The top left corner has the value n^2 - 2(n - 1).
* - The top right has the value n^2 - 3(n - 1).
*
* Furthermore, the number of elements on the diagonal is 2n - 1.
*/
public String run() {
int numPrimes = 0;
for (int n = 1; ; n += 2) {
for (int i = 0; i < 4; i++) {
if (Library.isPrime(n * n - i * (n - 1)))
numPrimes++;
}
if (n > 1 && numPrimes * 10 < n * 2 - 1)
return Integer.toString(n);
}
}
}