WEEK 1 computer practice project 2 -- monkey election dawang (Joseph's problem), Week 4 Joseph
Problem and code
/** Copyright (c) 2014, School of Computer Science, Yantai University * All rights reserved. * file name: test. cpp * Author: Xin Bin * Completion Date: July 15, January 30, 2015 * version number: v1.0 ** Problem description: Monkey election King (Joseph's problem ). * Input Description: number of people and number of people selected. * Program output: the number of the remaining persons. */# Include <iostream> using namespace std; int main () {cout <"Enter the number of monkeys:"; int n, I, m, die = 0, count = 0; // die indicates the number of outputted persons. count the number of outputted persons. cin> m; int a [1000]; for (I = 0; I <m; I ++) a [I] = 1; // first assign everyone a value of 1, indicating that the cout is left on the field <"Enter the number of the Loop:"; cin> n; for (I = 0; I <m; I ++) {if (a [I] = 1) count ++; // continue counting if (count = n) people who are still on the court. // once the number of people is selected, the value of this person changes to 0 and the game is exited, at the same time, count is changed back to 0, and the number of outgoing users increases by 1 {die ++; a [I] = 0; count = 0;} if (die = s-1) // when one person is left, the cycle ends break; if (I = s-1) // when the number of people is the last, return to the first person I =-1 ;} for (I = 0; I <m; I ++) if (a [I] = 1) cout <"the last number left is: "<I + 1; return 0 ;}
Running result:
Learning comprehension: I have done this before. I initialized the number of all people to 1, and changed it to 0 when I reached that number. At the same time, I recorded the number of people who had been eliminated. when there was only one person left, after the cycle ends, find the number of the person whose number is 1.