Joseph Problem (c + + implementation)

Source: Internet
Author: User

Description: Joseph problem: There are n monkeys, in the clockwise direction of a circle King (numbering from 1 to N), from the beginning of the 1th number, counting to M, the number of the monkey out of the circle, the rest of the monkeys continue to count from 1 onwards. In this way, until there is only one monkey in the circle, this monkey is the Monkey King, programming for input n,m, output the last Monkey King number.

Input: Each line is two integers separated by a space, the first is N, the second is m (0 < M, n < 300). The last line is: 0 0

Output: For each line of input data (except the last line), the output data is also a line, that is, the last monkey's number

Input

6 2

12 4

8 3

0 0

Output

5

1

7

Analysis: Monkeys can be represented by an array, the value of the array is the number of the monkey, when a monkey out of the code to change the number to 0

Indicating that the monkey was out of the game, when the last one left is a value not 0, the value is the monkey number.

1#include <iostream>2 using namespacestd;3 4  intMain ()5 {6      intN, M;7      inta[ -];8       while(Cin >> n >> m) &&! (n = =0&& m = =0))9      {Ten           for(inti =0; I < n; i++) OneA[i] = i +1; A          intk = n;//mark the rest of the monkeys -          intj =0;//tagged m -           while(k>1) the          { -               -               for(inti =0; I < n; i++) -              { +                  if(A[i] = =0) -                      Continue; +                  Else AJ + +; at                  if(j = m)//the monkey number out of the ring becomes 0. -                  { -A[i] =0; j =0; k--; -                  } -              } -          } in           for(inti =0; I < n; i++) -          { to              if(A[i]! =0) +cout << A[i] <<Endl; -          } the      } *System"Pause"); $      return 0;Panax Notoginseng}

Joseph Problem (c + + implementation)

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.