File tree Expand file tree Collapse file tree 1 file changed +18
-10
lines changed
project_euler/problem_301 Expand file tree Collapse file tree 1 file changed +18
-10
lines changed Original file line number Diff line number Diff line change 33
33
"""
34
34
35
35
36
- def solution (n : int = 2 ** 30 ) -> int :
36
+ def solution (exponent : int = 30 ) -> int :
37
37
"""
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
39
43
>>> solution(2)
40
- 2
41
- >>> solution(2 ** 10)
44
+ 3
45
+ >>> solution(10)
42
46
144
47
+ >>> solution(30)
48
+ 2178309
43
49
"""
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
50
58
51
59
52
60
if __name__ == "__main__" :
You can’t perform that action at this time.
0 commit comments