Joseph问题
// Joseph's Problem
// input: n,m -- the number of persons, the inteval between persons
// output: -- return the reference of last person
int josephus0(int n, int m)
{
if (n == 2) return (m%2) ? 2 : 1;
int v = (m+josephus0(n-1,m)) % n;
if (v == 0) v = n;
return v;
}
int josephus(int n, int m)
{
if (m == 1) return n;
if (n == 1) return 1;
if (m >=n) return josephus0(n,m);
int l = (n/m)*m;
int j = josephus(n - (n/m), m);
if (j <= n-l) return l+j;
j -= n-l;
int t = (j/(m-1))*m;
if ((j % (m-1)) == 0) return t-1;
return t + (j % (m-1));
}
完整代码:
#include <iostream>
#include <list>
using
std::cout;
using
std::endl;
using
std::cin;
using
std::list;
int
main()
{
int
total = 0;
cout <<
"Please input total number of people : "
;
cin >> total;
int
number = 0;
cout <<
"Please input selected number : "
;
cin >> number;
/* If number = 3
* f(1) = 0
* f(2) = 1 = (f(1) + 3) % 2
* f(3) = 1 = (f(2) + 3) % 3
* f(4) = 0 = (f(3) + 3) % 4
* f(5) = 3 = (f(4) + 3) % 5
* ...
* f(n) = x = (f(n-1) + 3) % n
* */
int
last = 0;
// f(1) = 0
for
(
int
i = 2; i <= total; ++i)
{
last = (last + number) % i;
}
cout <<
"The last one is : "
<< last + 1 << endl;
return
0;
}