forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsol1.py
57 lines (40 loc) · 1.06 KB
/
sol1.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
Project Euler Problem 136: https://projecteuler.net/problem=136
Singleton Difference
By change of variables
x = y + delta
z = y - delta
The expression can be rewritten:
x^2 - y^2 - z^2 = y*(4*delta - y) = n
The algorithm loops over delta and y, which is restricted in upper and lower limits,
to count how many solutions each n has.
In the end it is counted how many n's have one solution.
>>> solution(100)
25
"""
N = 50000000
def solution(n_limit: int = N) -> int:
"""
Define n count list and loop over delta, y to get the counts, then check
which n has count == 1.
>>> solution(3)
0
>>> solution(10)
2
>>> solution(110)
26
"""
n_sol = [0] * n_limit
for delta in range(1, (n_limit + 1) // 4):
for y in range(4 * delta - 1, delta, -1):
n = y * (4 * delta - y)
if n >= n_limit:
break
n_sol[n] += 1
ans = 0
for i in range(n_limit):
if n_sol[i] == 1:
ans += 1
return ans
if __name__ == "__main__":
print(f"{solution() = }")