This is the recursively rendered resolution of the Josephus problem , where n
is equal to the number of people in the circle, and k
is the step number to be given to the next person.
#include <iostream>
using namespace std;
int f(int n, int k){
if(n==1) return 1;
return (((f(n-1, k) + k-1)%n)+1);
}
int main(){
unsigned int n, k;
cin >> n >> k;
cout << f(n, k) << endl;
}
As you can see the algorithm works, however I would like to know how it works, I did not understand how it arrives at the end result.
My problem is with f(n, k) = (f(n-1, k) + k-1)%n + 1)
, I wonder how this can return the value corresponding to the last person to stay alive in the circle. I would also like to know what each return value of f(n-1, k)
with each recursion means, because for me the only one that makes sense is the last, which is the end result.