首页 > 代码库 > 14.约瑟夫环问题

14.约瑟夫环问题

http://zhedahht.blog.163.com/blog/static/2541117420072250322938/

http://en.wikipedia.org/wiki/Josephus_problem

证明略。

//f(1,m)=0
//f(n,m)=[f(n-1,m)+m]%n (n>=2)
int LastRemaining_Solution2(int n, unsigned int m)
{
    // invalid input
    if(n <= 0 || m < 0)
        return -1;

    // if there are only one integer in the circle initially,
    // of course the last remaining one is 0
    int lastinteger = 0;

    // find the last remaining one in the circle with n integers
    for (int i = 2; i <= n; i ++) 
        lastinteger = (lastinteger + m) % i;

    return lastinteger;
}