1.Numbered 1, 2,... N n individuals sitting around a circle, contract number is k (1 < = k < = n), people started to count off from 1 to m the man out, it's the next and started to count off from 1, count to m the dequeue and so on, until all out, creating a team number sequence.
/*
* funtion: Josephu
* parameter:
* @ the number of circle
* @ the interval No
* return value: the winer number
*/
/*eg1 :With an array of implementation */
int josephu(int n,int m)
{
int i,j = 0;
int flag;
int buff[N];
int *buff = (int *)malloc(n * sizeof(int)) ;
for(i = 0;i < N; i++)
buff[i] = 1;
for(i = 1; i < n; i++)
{
flag = 0;
if(j == n) j = 0;
while(flag < m)
{
if(buff[j])
flag ++;
j ++ ;
}
buff[j - 1] = 0;
printf("the %dth man is exit,the no is %d\n",i,j);
}
free(buff);
return j;
}
/*eg2 :Implemented with a linked list */
typedef int Datatype;
typedef struct _LinkNode_{
struct _Linknode_ *next;
Datatype index;
}Linknode;
Linknode *createlinknode()
{
Linknode *head = (Linknode *)malloc(sizeof(Linknode));
head->next = NULL;
return head;
}
int josephu_algorithm(int n,int m)
{
LinkNode *head,tail;
int i,j;
head = createlinknode();
tail = head;
for(i = 1 ; i < n ; i++ )
{
tail->index = i
tail->next = createlinknode();
}
tail->index = i;
tail->next = head; //Buid two-way linked list
for(i = 1; tail != head ; i++)
{
for(j = 1; j < m; j ++)
{
tail = head;
head = head->next;
}
tail->next = head->next;
free(head);
head = tail->next;
printf("the %dth man is exit,the no is %d\n",i,j);
}
i = head->index;
free(head);
return i;
}
int main()
{
int n, m;scanf("%d%d", &n, &m);
printf("the final champion is %d\n", Josephu(n, m));
return 0;
}
2. How to to achieve the above functions without using recursive calls?
//Fibonacci ratched series recursive implementation method is as follows:
int Funct(int n)
{
if(n == 0) return 0;
if(n == 1) return 1;
return Funct(n) + Funct(n-1);
}
//
/*
* funtion: Fibonacci ratched series
* parameter:
* @ the Natural number
* return value: Fibonacci ratched series
*/
* Function: Fibonacci ratched series
* parameter:
* @ Natural numbers
* @ return value :The nth Fibonacci number
*/
int Funct(int n)
{
int a=0,b=1,c;
if(n == 0 || n == 1) c = 1;
else
{
for(i = 2; i < n;i++)
{
c = a + b;
a = b;
b = c;
}
return c;
}