Algorithm for solving Joseph ring problem C language source code

Source: Internet
Author: User
Tags continue count printf

Joseph algorithm: n Individuals in a circle, each has a different number, select a person as the starting point, and then clockwise from 1 to K number, every number to K of the people out of the circle, circle narrowing, and then continue from the next person from 1 to K number, repeat the above process. The original number of the person who asked for the last launch circle.

Idea: Follow the above algorithm to let people out of the circle, until there are n-1 individuals to roll out the circle, and then get the last one out of the circle of the number of people.

Program: The number of people sitting in a circle does not need to be ordered

#define N 100
int yuesefu1 (int data[],int sum,int k)
{
int i=0,j=0,count=0;
while (count<sum-1)
{
if (data[i]!=0)/* Current person in the circle * *
j + +;
if (j==k)/* If the person should exit the circle * *
{
Data[i]=0;/*0 said not in the circle.
count++;/* exit number plus 1*/
j=0;/* the number of new numbers * *
}
i++;/* judge the next person
if (i==sum)/* Surround in a circle * *
i=0;
}
for (i=0;i<sum;i++)
if (data[i]!=0)
Return data[i];/* returns the last person's number * *
}

void Main ()
{
int data[n];
int i,j,total,k;
printf ("\nplease input the number of every people.\n");
for (i=0;i<n;)/* For people in the circle to arrange the number * *
{
int input;
scanf ("%d", &input);
if (input==0)
Break;/*0 means end of input/
for (j=0;j<i;j++)/* Check number is duplicate * *
if (data[j]==input)
Break
if (j>=i&&input>0)/* No duplicates, record number, continue to enter * *
{
Data[i]=input;
i++;
}
Else
printf ("\ndata error.") Re-input: ");
}
Total=i;
printf ("\nyou have input:\n");
for (i=0;i<total;i++)
{
if (i%10==0)
printf ("\ n");
printf ("%4d", Data[i]);
}
printf ("\nplease input a number to count:");
scanf ("%d", &k);
printf ("\nthe last one ' s number is%d", YUESEFU1 (data,total,k));
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.