Skip to content

Instantly share code, notes, and snippets.

@quantumelixir
Created November 7, 2018 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quantumelixir/bf4b975a285bb627c8724ec822625c4c to your computer and use it in GitHub Desktop.
Save quantumelixir/bf4b975a285bb627c8724ec822625c4c to your computer and use it in GitHub Desktop.
The famous Josephus problem
# There are n men numbered 1 through n standing in a circle. Starting
# from the first, every m-th man is killed, continuing the process
# from the next man in the circle. Who is the last to be killed?
# recursive
def l(n, m):
if n == 1: return 0
f = (m-1) % n
k = l(n-1, m)
if k <= n-1-(f+1): return k+f+1
return k-(n-f-1)
def L(n, m): return 1 + l(n, m)
# iterative
def l0(N, m):
k = 0
for n in range(2, N+1):
f = (m-1) % n
k = k+f+1 if k <= n-1-(f+1) else k-(n-f-1)
return k
def L0(n, m): return 1 + l0(n, m)
n, m = 10**6, 2
print(L0(n, m))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment