Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit edb6544

Browse files
Update josephus_improved.py
The equation to the Josepus problem, W(n) = 2L + 1, has a constraint in which L < 2^a (The biggest power of 2 inside the number of soldiers, in this case the variable p). This means if n is a power of 2, the winning position will always be 1, so the formula would be wrong.
1 parent 0d0c7df commit edb6544

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

‎josephus_improved.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,11 @@ def josephus_v2(people, step=2):
1212
# the loop runs for O(floor(logN)) time
1313
while p*2 < N:
1414
p = p*2
15-
print((2*(N-p))+1)
15+
# If N is a power of 2, should return 1. So let's check if L (N-p) is < p
16+
if N-p >= p:
17+
print(1)
18+
else:
19+
print((2*(N-p))+1)
1620

1721
num = int(input("Enter the number of soldiers: "))
1822
soldiers = [i for i in range(1, num+1)] # generates a list of 1..num

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /