Skip to content

Commit 0b83476

Browse files
authored
Add files via upload
1 parent a6331e3 commit 0b83476

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

josephus_improved_v3.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# The effective time complexity of this improved version is O(1).
2+
# For the problem statement, refer `josephus.py`
3+
4+
def josephus_v3(soldiers):
5+
# Convert to binary.
6+
binary = bin(soldiers)
7+
# Get the first digit and put it as last.
8+
shift = '0b' + binary[3::] + binary[2:3:]
9+
# Convert to decimal.
10+
return int(shift, 2)
11+
12+
winning = josephus_v3(soldiers=41)
13+
print(winning) #Winning Soldier: 19
14+
15+
winning = josephus_v3(soldiers=100)
16+
print(winning) #Winning Soldier: 73
17+
18+
winning = josephus_v3(soldiers=1000)
19+
print(winning) #Winning Soldier: 977
20+
21+
# Testing:
22+
test_josephus = {
23+
1: 1,
24+
2: 1,
25+
3: 3,
26+
4: 1,
27+
5: 3,
28+
6: 5,
29+
7: 7,
30+
8: 1,
31+
9: 3,
32+
10: 5,
33+
11: 7,
34+
12: 9,
35+
13: 11,
36+
16: 1,
37+
41: 19
38+
}
39+
for soldiers, expected_winner in test_josephus.items():
40+
assert josephus_v3(soldiers=soldiers) == expected_winner

0 commit comments

Comments
 (0)