41个人围成一个圈从1号开始报数,每次报到3的人被杀掉,求最后幸存的人的编号
python:
def move(man, sep):
for i in range(sep):
item = man.pop(0)
man.append(item) # 加到列表后面
def play(man=41, sep=3, rest=2):
print("总共%d个人,每报数到%d的人***,最后剩余%d个人" % (man, sep, rest))
man = [i for i in range(1, man+1)] # [1,man-1)
print("玩家队列:", man)
sep -= 1
while len(man) > rest:
move(man, sep)
print('kill', man.pop(0))
return man
servive = play() # 返回列表
print("最后逃生的人编号是:", servive)
C++:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
//freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
int n;
scanf("%d",&n);
int a[100];
for(int i = 1; i <= n; i++)
a[i] = i;
int cnt = 0;
while(1)
{
int num = 1;
for(int i = 1; i <= n; i++)
{
cnt++;
if(cnt%3)
a[num++] = a[i];
}
n=num-1;
if(n<=2) break;
}
printf("Final survivor: ");
for(int i = 1; i <= n; i++)
printf("%d ",a[i]);
return 0;
}