The question of a prison guard is an amnesty for a certain kingdom, let a warder n times through a row of locked n cells, each through a set of rules to rotate the lock, each rotation once, the original lock was opened, the original opened was locked; after N times, the door is open, the inmates in the cell release, Otherwise, the prisoner shall not be released. The rules for turning locks are this, for the first time through a cell, to rotate every door lock, that is, to open all the locks; the second time through the cell, starting from the second rotation, every other rotation once; K-time through cells, starting from the beginning of the rotation of the k, the rotation between each k-1; ask through n times, The locks on those cells are still open?
Three ways:
Status of locks in all methods: 1 for lock, 0 for open
1. Pure violence Law
C + + code:
#include <iostream>
using namespace std;
int main () {
int n,*prisoner;
cin>>n;
Prisoner=new int[n+1];
for (int i=0;i<=n;i++)
prisoner[i]=1;
for (int i=1;i<=n;i++) //i---> indicates that the Warder was the number
of the first rounds of the for (int j=i;j<=n;j=j+i)//j---> The locks to be changed PRISONER[J]=1-PRISONER[J];
for (int i=1;i<=n;i++)
if (prisoner[i]==0)
cout<<i<< "";
return 0;
}
2, the use of factors
C + + code:
The number of factor number is used to derive the frequency of the Lock intermediate transformation State of each number
//eg i=4, its factor has 1,2,4, so he will change the state in the first 1,2,4 wheel.
#include <iostream>
using namespace std;
int main () {
int n,*prisoner;
cin>>n;
Prisoner=new int[n+1];
for (int i=0;i<=n;i++)
prisoner[i]=1;
for (int i=1;i<=n;i++)
{
int count=1;
for (int j=2;j<=i;j++)
if (i%j==0)
count++;
if (count%2==0)
prisoner[i]=1;
else
prisoner[i]=0;
}
for (int i=1;i<=n;i++)
if (prisoner[i]==0)
cout<<i<< "";
return 0;
}
3, find the law
C + + code:
Use the rule to Judge
/rule: When a lock is labeled as a square of a number, then it will open at last
eg. (1 of them are locked and 0 are open)
Marking of the Lock: 1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16
Last Status: 0 1 1 0 1 1 1 1 0 1 1 1 1 1 1 0
#include <iostream> #include <math.h> using namespace std; int main () {int N,*priso
Ner
cin>>n;
Prisoner=new int[n+1];
for (int i=0;i<=n;i++) prisoner[i]=1;
for (int i=1;i<=sqrt (n); i++) {int temp=i*i;
if (temp<=n) prisoner[temp]=0;
for (int i=1;i<=n;i++) if (prisoner[i]==0) cout<<i<< "";
return 0; }