Monkey election king

Source: Internet
Author: User

Today we want to write "Monkey King", a classic-to-end classical C ++ programming question.

There are n monkeys in a circle, from 1-N number, we decided to select a king. After negotiation, the rule for selecting the king is: report the number of monkeys starting from 1, report the number of monkeys reporting to k, and then continue reporting 1 to K from the next one ......, The last one left is the king. Require programming input N and K from the keyboard, and output the Monkey number that becomes the king.

[Input]

One row has two integers, N and K.

[Output]

A positive integer representing the number of the Monkey King

[Example input]

3 2

[Sample output]

3

Question:

Common Code:

#include <stdio.h>int main(){    int N;    int a[1000];    scanf("%d", &N);    int count = 0, number = N;    for (int i = 0; i < N; i++)        a[i] = i + 1;    while (number > 1)    {        for (int i = 0; i < N; i++)        {            if (a[i] == 0)                continue;            count++;            if (count == 3)            {                a[i] = 0;                count = 0;                number--;            }        }    }    for (int i = 0; i < N; i++)        if (a[i] != 0)            printf("%d", a[i]);     return 0;}

Master code (think for a while)

#include<iostream>using namespace std;int main(){    int n,m,k,r,q;    cin>>n>>k;    m=n*k;    while(n>m)    {        r=(m-n)%(k-1)l        if(r==0)            r=k-1;        q=(m-n-r)/(k-1);        m=k*q+r;    }    cout<<m;    return 0;    }

Daxie's code (that is, me)

#include<iostream>using namespace std;int main(){    int n,k;    cin>>n>>k;    int i,ans=0;    for(i=2;i<=n;i++)        ans=(ans+k)%i;    cout<<ans+1;    return 0;}

Graph and truth (pay attention to the code length)

 

Monkey election king

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.