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