8
This is the resolution, recursively made in C++, of josephus problem, where n
is equal to the number of persons in the circle, and k
is the number of step to be taken for 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, but I would like to know how it works, I did not understand how it arrives at the final 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 left alive in the circle. I would also like to know what each return value of f(n-1, k)
each recursion means, because for me the only one that makes sense is the last one, which is the final result.
I couldn’t understand, you’re saying that the return number is the position of the person relative to how many a in the circle in the current recursion?
– Danilo Lucas
Exactly that.
– mutlei
I believe that’s not it, I manually made all the returns and they do not match the person who should be withdrawn that time, and there comes a point that until the...
– Danilo Lucas
I edited the answer.
– mutlei