100 doors problem(Modified) using Python2 min read
Posted On August 25, 2019
There are 100 doors and a person walks through it in such a way that:-
In first walk he opens first door
In second walk he opens each door that is a multiple of two but close door 2 later.
Similarly in i-th walk he opens each door that is a multiple of i and close i-th door later.
Which doors are open at end?
The basic approach would be to to start from 2 and go till 100 and keep the track of which doors are opened and which are closed.Then print the no. of open doors.But its time complexity will be:-O(n2)
Code in Python
#This function changes the current position of door,if the door is open then it is closed otherwise it is opened
n=100 #No. of doors(Can be changed for a general n-doors problem.)
doors=*n #Making a list and initializing them with 0
#Here 0 means that door is close and 1 means that door is open
for i in range(2,n+1):
count=0#Counter to keep track of open doors
for i in range(n):
print(i+1,end=" ")#Printing the open doors
print() #Inserting a new line after printing all doors that are open
print("\n No. of open doors are",count)#Total no. of open doors
From above output it can be observed that only those doors are opened that are not prime.So,we can directly print all those numbers that are not prime rather than keeping track of which doors are opened or not.
if n%2==0 or n%3==0:#Used so that we can skip 5 numbers in each iteration
if n%i==0 or n%(i+2)==0:
n=100#It can be changed with the number of doors
print(*[str(i)+" " if not_prime(i) else '' for i in range(1,n+1)],end=" ")
Reference:- https://freshlybuilt.com/100-doors-problem-using-python/ Problem Statement This is a general form of 100 doors problem.Here you have n doors.All doors are initially closed.m persons walk through all…