For Jos Loops, the key to simplifying the problem and code with recursive formulas is to find the correct recursive formula, which can be found using an example.
(Poor math skills, have to make a watch to find the law)
For the convenience of the remainder operation, the index number 1---n is indicated as 0--(n-1) example n=11,m=3, that is, 11 people count off, check in 3 of the people out
Subscript 0 1 2 3 4 5 6 7 8 9
Serial 1 2 3 4 5 6 7 8 9 10 11
One, 4 5 6 7 8 9 10 11 1 2
Two, 7 8 9 10 11 1 2 4 5
Three, ten, 1 2 4 5 7 8
Four, 2 4 5 7 8 10 11
Five, 7 8 10 11 2 4
Six, 2 4 7 8
Seven, 7 8 11 2
Eight, 2 7 8
Nine, 2 7
Ten, 7
Push to the last known survivor is number 7th (red mark), corresponding subscript (this subscript should be the most primitive corresponding) is 6, (in fact, regardless of why the value of the last person n,m the subscript is 0).
Observe the red flag, you can find that starting from the first line, each time the 7 corresponding subscript is pushed forward three bits (in their own line of the push);
From the top to the bottom 7 corresponding subscript 6->3->0->6->3->0->3->0->1->1->0;
Now to do is to start from the right to the left to launch the most primitive subscript, plus one is the survivor number;
The rollout process is about to shift the current coordinates to the right three-bit, it is not difficult to find that the number of people should be pushed down ~-~;
Formula: (current subscript +m)% (the number of people on the previous line corresponding to the current row);
Also take 11-3 for example: (0+3)%2=1---(1+3)%3=1--(1+3)%4=0--(0+3)%5=3 ... (omitted) ..... (3+3)%11=6; draw the final subscript, plus one for the serial number 7;
Code Rx:
#include <iostream>
using namespace Std;
int jos (int n,int m)
{
int i,k=0;
for (i=2;i<=n;i++)
k= (k+m)%i;
return k+1;
}
int main ()
{
int n,m;
while (CIN>>N>>M)
Cout<<jos (n,m) <<endl;
return 0;
}
Of course, we can find this law-.-by setting the variable as the letter;
First article, Jos