Problem:
There is a tree (initial height- 1mt) which grows twice its current length in 1st cycle and grows by 1 mt in 2nd cycle and then again twice its current length in 3rd cycle and by 1mt in 4th cycle and so on.
Find the height after Nth cycle.
Input is in form of T and N(i), where T is number of input and N(i) is the cycle number for which height is required.
Also, 0<=T<=10 and 0<=N<=30
Sample Input:
2
0
3
Sample Output:
1
6
Explanations:- T=2, so we need to find height after 0th cycle and after 3rd cycle
Solution:
$T = <STDIN>;
if($T<0 or $T>10)
{
exit;
}
@arr;
$h=0;
for(my $i=0;$i<$T;$i++)
{
$arr[$i] = <STDIN>;
if($arr[$i]<0 or $arr[$i]>30)
{
exit;
}
}
for(my $j=0;$j<@arr;$j++)
{
for(my $k=0;$k<=$arr[$j];$k++)
{
if($k%2 == 0)
{
$h = $h + 1;
}
else{
$h = 2 * $h;
}
}
print "$h\n";
$h=0;
}
Tips:
There is a tree (initial height- 1mt) which grows twice its current length in 1st cycle and grows by 1 mt in 2nd cycle and then again twice its current length in 3rd cycle and by 1mt in 4th cycle and so on.
Find the height after Nth cycle.
Input is in form of T and N(i), where T is number of input and N(i) is the cycle number for which height is required.
Also, 0<=T<=10 and 0<=N<=30
Sample Input:
2
0
3
Sample Output:
1
6
Explanations:- T=2, so we need to find height after 0th cycle and after 3rd cycle
Solution:
$T = <STDIN>;
if($T<0 or $T>10)
{
exit;
}
@arr;
$h=0;
for(my $i=0;$i<$T;$i++)
{
$arr[$i] = <STDIN>;
if($arr[$i]<0 or $arr[$i]>30)
{
exit;
}
}
for(my $j=0;$j<@arr;$j++)
{
for(my $k=0;$k<=$arr[$j];$k++)
{
if($k%2 == 0)
{
$h = $h + 1;
}
else{
$h = 2 * $h;
}
}
print "$h\n";
$h=0;
}
Tips:
- % is modulus, used to find if number is even or odd
No comments:
Post a Comment