C Exercise 69
100 Classic C Language Examples
**Problem:** n people stand in a circle and are numbered in order. Starting from the first person, they count off (from 1 to 3), and whoever counts to 3 leaves the circle. The question is: which original number is the last person remaining?
**Analysis:** None.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. 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 the 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, that is, 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 who have left is not greater than the total, that is, at least one person remains
// This line cannot be written as m // At this point it is 7<8. The remaining person counting 1, 2, 3 himself would also leave, so there would be no output { if ( ( p i ) != 0 ) // If this person's number is not 0, start counting and add 1; the method used here is to reset the number of the person who counts to 3 back to 0 { k ++; } if ( k == 3 ) { k = 0 ; // Reset the count to zero, that is, the next person starts counting from 1 ( p i ) = 0 ; // Reset the number of the person who counted to 3 to 0 m ++; // Increment the number of people who have left by 1 } i ++; // Move the pointer forward if ( i == n ) // This line is crucial: when reaching the end of the queue, the pointer must be reset to the head // And it can only be placed after i++, because only after i++ can i==n be possible { i = 0 ; } } printf ( " The person remaining now is: " ) ; for ( loop = 0 ; loop < n ; loop ++ ) { if ( num [ loop ] != 0 ) { printf ( " No. %2d \ n " , num [ loop ] ) ; } } } The output of the above program is:
Please enter the number of people in this circle:
8
现在剩下的人是: 7号