project-euler/128_hexagonal_tile_diff.py

43 lines
743 B
Python
Raw Normal View History

2023-03-26 17:21:44 +02:00
#!/usr/bin/env python3
def primes(n):
sieve = [True] * n
for p in range(2, int(n**0.5)):
if not sieve[p]:
continue
for i in range(p**2, n, p):
sieve[i] = False
return [False, False] + sieve[2:]
def is_prime(p):
if p >= len(sieve):
raise LimitError
return sieve[p]
def getnum(n, c):
m = n//6
if c:
return 3*(m-1)*m + 2
return 3*m*(m+1) + 1
sieve = primes(10**6)
target = 2000
c = 2
n = 6
while c < target:
n += 6
if not is_prime(n-1):
continue
c += is_prime(n+1) and is_prime(2*n + 5)
if c == target:
flag = True
break
c += is_prime(n+5) and is_prime(2*n-7)
else:
flag = False
print(getnum(n, flag))