@@ -18,18 +18,19 @@ We will try to find a pattern expressing the answer for the problem $J_{n, k}$ t
18
18
19
19
Using brute force modeling we can construct a table of values, for example, the following:
20
20
21
- $$ \begin{matrix} n\setminus k & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\cr
22
- 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\cr
23
- 2 & 2 & 1 & 2 & 1 & 2 & 1 & 2 & 1 & 2 & 1\cr
24
- 3 & 3 & 3 & 2 & 2 & 1 & 1 & 3 & 3 & 2 & 2\cr
25
- 4 & 4 & 1 & 1 & 2 & 2 & 3 & 2 & 3 & 3 & 4\cr
26
- 5 & 5 & 3 & 4 & 1 & 2 & 4 & 4 & 1 & 2 & 4\cr
27
- 6 & 6 & 5 & 1 & 5 & 1 & 4 & 5 & 3 & 5 & 2\cr
28
- 7 & 7 & 7 & 4 & 2 & 6 & 3 & 5 & 4 & 7 & 5\cr
29
- 8 & 8 & 1 & 7 & 6 & 3 & 1 & 4 & 4 & 8 & 7\cr
30
- 9 & 9 & 3 & 1 & 1 & 8 & 7 & 2 & 3 & 8 & 8\cr
31
- 10 & 10 & 5 & 4 & 5 & 3 & 3 & 9 & 1 & 7 & 8\cr
32
- \end{matrix} $$
21
+ $$ \begin{array}{ccccccccccc}
22
+ n\setminus k & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\\\
23
+ 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\\\
24
+ 2 & 2 & 1 & 2 & 1 & 2 & 1 & 2 & 1 & 2 & 1 \\\\
25
+ 3 & 3 & 3 & 2 & 2 & 1 & 1 & 3 & 3 & 2 & 2 \\\\
26
+ 4 & 4 & 1 & 1 & 2 & 2 & 3 & 2 & 3 & 3 & 4 \\\\
27
+ 5 & 5 & 3 & 4 & 1 & 2 & 4 & 4 & 1 & 2 & 4 \\\\
28
+ 6 & 6 & 5 & 1 & 5 & 1 & 4 & 5 & 3 & 5 & 2 \\\\
29
+ 7 & 7 & 7 & 4 & 2 & 6 & 3 & 5 & 4 & 7 & 5 \\\\
30
+ 8 & 8 & 1 & 7 & 6 & 3 & 1 & 4 & 4 & 8 & 7 \\\\
31
+ 9 & 9 & 3 & 1 & 1 & 8 & 7 & 2 & 3 & 8 & 8 \\\\
32
+ 10 & 10 & 5 & 4 & 5 & 3 & 3 & 9 & 1 & 7 & 8 \\\\
33
+ \end{array} $$
33
34
34
35
And here we can clearly see the following ** pattern** :
35
36
@@ -44,15 +45,15 @@ So, we found a solution to the problem of Joseph, working in $O(n)$ operations.
44
45
45
46
Simple ** recursive implementation** (in 1-indexing)
46
47
47
- ```
48
+ ``` cpp
48
49
int josephus (int n, int k) {
49
50
return n > 1 ? (joseph(n-1, k) + k - 1) % n + 1 : 1;
50
51
}
51
52
```
52
53
53
54
**Non-recursive form** :
54
55
55
- ```
56
+ ```cpp
56
57
int josephus(int n, int k) {
57
58
int res = 0;
58
59
for (int i = 1; i <= n; ++i)
@@ -81,7 +82,7 @@ Also, we need to handle the case when $n$ becomes less than $k$ - in this case,
81
82
82
83
** Implementation** (for convenience in 0-indexing):
83
84
84
- ```
85
+ ``` cpp
85
86
int josephus (int n, int k) {
86
87
if (n == 1)
87
88
return 0;
0 commit comments