1. 循环
#include <iostream>
using namespace std;
int joseph(const int n, const int m)
{
int* arr = new int[n];
for (int i = 0; i < n; ++i) arr[i] = 1;
int i = 0;
int j = 0;
int count = n;
while (count > 1)
{
if (arr[i] == 1)
{
if (++j == m)
{
arr[i] = 0;
--count;
j = 0;
}
}
if (++i == n) i = 0;
}
int res = 0;
for (int i = 0; i < n; ++i)
{
if (arr[i] == 1)
{
res = i;
break;
}
}
delete[] arr;
return res;
}
2. 递归
#include <iostream>
using namespace std;
int joseph(const int n, const int m)
{
if (n < 1 || m < 1) return -1;
if (n == 1) return 0;
return (joseph(n - 1, m) + m) % n;
}