C Exercise Example 69
Title:There are n people sitting in a circle, numbered in order. Counting starts from the first person (counting from 1 to 3). Anyone who counts to 3 leaves the circle. Ask: what is the original number of the last person left?
Program analysis:None.
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
//
#include <stdio.h>
void main()
{
int num[50],n,*p,j,loop,i,m,k;
printf("Please enter the number of people in this circle:\n");
scanf("%d",&n);
p=num;
// Start numbering these people
for (j=0;j<n;j++)
{
*(p+j)=j+1;
}
i=0;// i is used for counting, i.e., to move the pointer forward
m=0;// m records the number of people who have left the circle
k=0;// k counts off 1, 2, 3
while(m<n-1)// When the number of people leaving is not greater than the total number, i.e., the number staying is at least one.
// This line cannot be written as m<n, because suppose there are 8 people, when 6 people have exited, at this time it still carries out an exit, i.e., m++,
// At this point, it is 7<8, the remaining person calls out 1, 2, 3 by themselves, then they also exit, and there will be no output.
{
if (*(p+i)!=0)// If the number on this person's head is not 0, start counting and add 1. The method used here is that the person who counts to 3 has their head number reset to 0.
{
k++;
}
if (k==3)
{ k=0; // Reset the count, so the next person starts counting from 1
*(p+i)=0;// Reset the number of the person who reports 3 to 0
m++; // Exit count +1
}
i++; //Move pointer forward
if (i==n)// This line is crucial: if the end of the queue is reached, reset the pointer to the head.
// And it can only be placed after i++, because only after i++ is it possible that i==n
{
i=0;
}
}
printf("The remaining people are:");
for (loop=0;loop<n;loop++)
{
if (num[loop]!=0)
{
printf("Number %2d\n",num[loop]);
}
}
}
The result of executing the above program is:
请输入这一圈人的数量: 8 现在剩下的人是: 7号other extensions