Problem:
There are 500 closed doors along a corridor, numbered from 1 to 500. A person walks through the corridor and opens each door. Another person walks through the corridor and closes every alternate door. Continuing in this manner, the i-th person comes and toggles the position of every i-th door starting from door i. You are to determine exactly how many doors are open after the 500-th person has walked through the corridor.
Sample Input:
500
Sample Output:
no of doors opened after 500-th person walked through the corridor having 500 doors is 22
Solution:
$num = 500;
@arr;
for(my $i=0;$i<$num;$i++)
{
$arr[$i] = 0;
}
for(my $i=0;$i<$num;$i++)
{
for(my $j=$i;$j<$num;$j++)
{
if($arr[$j] == 0)
{
$arr[$j]=1;
}
elsif($arr[$j] == 1)
{
$arr[$j]=0;
}
$j = $j + $i;
}
}
$tmp = 0;
foreach(@arr){
if($_ == 1)
{
$tmp++;
}
}
print "no of doors opened after $num-th person walked through the corridor having $num doors is $tmp";
Tips:
There are 500 closed doors along a corridor, numbered from 1 to 500. A person walks through the corridor and opens each door. Another person walks through the corridor and closes every alternate door. Continuing in this manner, the i-th person comes and toggles the position of every i-th door starting from door i. You are to determine exactly how many doors are open after the 500-th person has walked through the corridor.
Sample Input:
500
Sample Output:
no of doors opened after 500-th person walked through the corridor having 500 doors is 22
Solution:
$num = 500;
@arr;
for(my $i=0;$i<$num;$i++)
{
$arr[$i] = 0;
}
for(my $i=0;$i<$num;$i++)
{
for(my $j=$i;$j<$num;$j++)
{
if($arr[$j] == 0)
{
$arr[$j]=1;
}
elsif($arr[$j] == 1)
{
$arr[$j]=0;
}
$j = $j + $i;
}
}
$tmp = 0;
foreach(@arr){
if($_ == 1)
{
$tmp++;
}
}
print "no of doors opened after $num-th person walked through the corridor having $num doors is $tmp";
Tips:
- Simple solution is nearest square root ie square root of 500 is 22.36, so answer is 22
No comments:
Post a Comment