forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp058.py
More file actions
32 lines (27 loc) · 1003 Bytes
/
p058.py
File metadata and controls
32 lines (27 loc) · 1003 Bytes
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
#
# 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
#
import eulerlib, fractions, itertools
# 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.
def compute():
TARGET = fractions.Fraction(1, 10)
numprimes = 0
for n in itertools.count(1, 2):
for i in range(4):
if eulerlib.is_prime(n * n - i * (n - 1)):
numprimes += 1
if n > 1 and fractions.Fraction(numprimes, n * 2 - 1) < TARGET:
return str(n)
if __name__ == "__main__":
print(compute())