Skip to content

Commit a42997e

Browse files
KumarUniverseKumarUniverse
KumarUniverse
authored and
KumarUniverse
committed
Optimized solution from O(n^2) to O(1) constant time
1 parent 96e6a1f commit a42997e

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

project_euler/problem_301/sol1.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,28 @@
3333
"""
3434

3535

36-
def solution(n: int = 2 ** 30) -> int:
36+
def solution(exponent: int = 30) -> int:
3737
"""
38-
For a given integer n <= 2^30, returns how many Nim games are lost.
38+
For any given exponent x >= 0, 1 <= n <= 2^x.
39+
This function returns how many Nim games are lost given that
40+
each Nim game has three heaps of the form (n, 2*n, 3*n).
41+
>>> solution(0)
42+
1
3943
>>> solution(2)
40-
2
41-
>>> solution(2 ** 10)
44+
3
45+
>>> solution(10)
4246
144
47+
>>> solution(30)
48+
2178309
4349
"""
44-
loss_count = 0
45-
for i in range(1, n + 1):
46-
if (i ^ (2 * i) ^ (3 * i)) == 0:
47-
loss_count += 1
48-
49-
return loss_count
50+
# To find how many total games were lost for a given exponent x,
51+
# we need to find the Fibonacci number F(x+2).
52+
fib_ind = exponent + 2
53+
phi = (1 + 5 ** 0.5) / 2
54+
fib = (phi ** fib_ind - (phi - 1) ** fib_ind) / 5 ** 0.5
55+
nim_loss_count = int(fib)
56+
57+
return nim_loss_count
5058

5159

5260
if __name__ == "__main__":

0 commit comments

Comments
 (0)