project-euler/504_square_on_the_inside.py

49 lines
968 B
Python
Raw Normal View History

#!/usr/bin/env python3
2023-03-26 23:00:14 +02:00
from math import gcd
from itertools import combinations_with_replacement as combs
from math import sqrt
def points(a, b, c, d):
return (gcds[a][b] + gcds[b][c] + gcds[c][d] + gcds[d][a])//2 + 1
def is_square(n):
return sieve[n]
def refs(a,b,c,d):
r = [ (a,b,c,d),
(d,a,b,c),
(c,d,a,b),
(b,c,d,a),
(a,d,c,b),
(b,a,d,c),
(c,b,a,d),
(d,c,b,a)]
return list(set(r))
count = 0
m = 100
space = range(1, m+1)
gcds = [None for n in range(m+1)]
for a in range(1, m+1):
gcds[a] = [0] + [a*b - gcd(a,b) for b in range(1, m+1)]
sieve = [False] * 2*m**2
n = 1
while n**2 < len(sieve):
sieve[n**2] = True
n += 1
for a,b,c,d in combs(space, 4):
perms = [(a,b,c,d), (a,c,b,d), (a,c,d,b)]
wins = set()
for p in perms:
if not is_square(points(*p)):
continue
wins |= set(refs(*p))
count += len(wins)
print(count)