-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJosephusPermutation.py
More file actions
29 lines (25 loc) · 950 Bytes
/
JosephusPermutation.py
File metadata and controls
29 lines (25 loc) · 950 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Sample code #1 of the Josephus Permutation
# This problem combines recursive thinking, modular arithmetic,
# and efficient coding—making it an excellent practice problem for programmers.
def josephus(n, k):
"""Returns the position of the last person in the Josephus problem."""
if n == 1:
return 1
else:
# Recursively calculate the position
return (josephus(n - 1, k) + k - 1) % n + 1
# Example usage
n = 7 # Number of people
k = 3 # Step size
survivor = josephus(n, k)
print(f"The survivor is at position: {survivor}")
# Sample code #2 of the Josephus Permutation for larger inputs
def josephus_iterative(n, k):
"""Returns the position of the last person using an iterative approach."""
survivor = 0
for i in range(2, n + 1):
survivor = (survivor + k) % i
return survivor + 1
# Example usage
survivor = josephus_iterative(n, k)
print(f"The survivor is at position: {survivor}")