project-euler/165_intersections.py

49 lines
1.1 KiB
Python
Raw Normal View History

2023-03-25 17:24:17 +01:00
#!/usr/bin/env python3
from fractions import Fraction
from itertools import combinations
def solve(line1, line2):
x1, y1 = line1[0][0] - line1[1][0], line1[0][1] - line1[1][1]
x2, y2 = -line2[0][0] + line2[1][0], -line2[0][1] + line2[1][1]
xv, yv = line2[1][0] - line1[1][0], line2[1][1] - line1[1][1]
det = x1*y2 - y1*x2
if det == 0:
return None
p = det // abs(det)
det = abs(det)
n = p * (xv*y2 - yv*x2)
if not (0 < n < det) or not (0 < p * (x1*yv - y1*xv) < det):
return None
return (line1[1][0] + Fraction(n, det) * x1, line1[1][1] + Fraction(n, det) * y1)
l1 = (27, 44), (12, 32)
l2 = (46, 53), (17, 62)
l3 = (46, 70), (22, 40)
def blum(n):
s = 290797
for i in range(n):
s = pow(s, 2, 50515093)
yield s % 500
N = 5000
nums = list(blum(N*4))
lines = []
for i in range(0, len(nums)-3, 4):
line = (nums[i], nums[i+1]), (nums[i+2], nums[i+3])
lines.append(line)
points = []
for a, b in combinations(lines, 2):
p = solve(a, b)
if p == None:
continue
points.append(p)
print(len(set(points)))