この回答は、ヨセフス問題の要約であり、次の質問に対する回答でもあります。
- 何を
josephus(n-1,k)
指していますか?
- モジュラス演算子は何に使用されていますか?
これを呼び出すjosephus(n-1,k)
と、k 番目の人ごとに合計 n-1 回実行したことになります。(ジョージ・トムリンソンのコメントに合わせて変更)
The recursion keeps going until there is 1 person standing, and when the function returns itself to the top, it will return the position that you will have to be in to survive. The modulus operator is being used to help stay within the circle (just as GuyGreer explained in the comments). Here is a picture to help explain:
1 2
6 3
5 4
Let the n = 6 and k = 2 (execute every 2nd person in the circle). First run through the function once and you have executed the 2nd person, the circle becomes:
1 X
6 3
5 4
Continue through the recursion until the last person remains will result in the following sequence:
1 2 1 X 1 X 1 X 1 X X X
6 3 -> 6 3 -> 6 3 -> X 3 -> X X -> X X
5 4 5 4 5 X 5 X 5 X 5 X
When we check the values returned from josephus at n we get the following values:
n = 1 return 1
n = 2 return (1 + 2 - 1) % 2 + 1 = 1
n = 3 return (1 + 2 - 1) % 3 + 1 = 3
n = 4 return (3 + 2 - 1) % 4 + 1 = 1
n = 5 return (1 + 2 - 1) % 5 + 1 = 3
n = 6 return (3 + 2 - 1) % 6 + 1 = 5
Which shows that josephus(n-1,k) refers to the position of the last survivor. (1)
モジュラス演算子を削除すると、11 番目の位置が返されることがわかりますが、ここには 6 つしかないため、モジュラス演算子はカウントを円の境界内に保つのに役立ちます。(2)