3

The josephus problem can be solved by the below recursion:

 josephus(n, k) = (josephus(n - 1, k) + k-1) % n + 1
 josephus(1, k) = 1

How this recurrence relation has been derived?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Green goblin
  • 9,898
  • 13
  • 71
  • 100

2 Answers2

1

josephus(n, k) = (josephus(n - 1, k) + k-1) % n + 1 ...... (1)

To put it in simple words - starting with the "+1" in the formula. It implies that 1 iteration of the recurrence has already been done. Now, we would be left with n-1 persons/elements. We need to process n-1 elements recursively at intervals of k. But, now, since the last element to be removed was at kth location, we would continue from thereof. Thus, k-1 added. Further, this addition might upset the indexing of the array. Thus %n done to keep the array index within the bounds. Hope it is lucid and elaborate enough :) .

user1412066
  • 155
  • 3
  • 10
0

This paragraph is sufficient from wikipedia..

When the index starts from one, then the person at s shifts from the first person is in position ((s-1)\bmod n)+1, where n is the total number of persons. Let f(n,k) denote the position of the survivor. After the k-th person is killed, we're left with a circle of n-1, and we start the next count with the person whose number in the original problem was (k\bmod n)+1. The position of the survivor in the remaining circle would be f(n-1,k) if we start counting at 1; shifting this to account for the fact that we're starting at (k\bmod n)+1 yields the recurrence

f(n,k)=((f(n-1,k)+k-1) \bmod n)+1,\text{ with }f(1,k)=1\,,

Undo
  • 25,519
  • 37
  • 106
  • 129
Bhavuk Mathur
  • 1,048
  • 1
  • 12
  • 22
  • Honestly, I could not understand this sentence: `then the person at s shifts from the first person is in position`, there are two predicates. What does "shifts" mean? Can you explain more to me? I check the Chinese and Japanese version, but this sentence is not there. – Peter Lee Sep 22 '13 at 01:51