Calculate the number of squares from a rectangle

I am working on some PHP code, but I stick to the logic. I need to know the number of squares from a rectangle.

I can not implement this in PHP.

Please, help.

I tried this:

function getcount($length,$breadth,$count=0){ $min=min($length,$breadth); if($length>$breadth){ $length=$length-$min; $count++; return getcount($length,$breadth,$count); } else if($breadth>$length){ $breadth=$breadth-$min; $count++; return getcount($length,$breadth,$count); } else{ $count+=($length/$min); } return $count; } 

But some of them do not convey all use cases. And I do not know in what cases of use, does it fail?

+6
source share
2 answers

I think the easiest way to calculate the number of squares in a rectangle is to subtract the found squares from it when it completely disappears.

This works fine for me:

 function getcount($width,$height) { $total=0; while($width && $height) { if($width>$height) { $width-=$height; } else if($height>$width) { $height-=$width; } else { $width=0; $height=0; } $total+=1; } return $total; } echo getcount(5,3)."<br/>"; echo getcount(5,5)."<br/>"; echo getcount(11,5)."<br/>"; 

Output:

 4 1 7 
+7
source

In my opinion, there is nothing wrong with your code. The output from the code in the OP is exactly the same as the code output in the accepted answer . You can run this (where getcount() is a function from OP, and getcount2() is a function from Balaz Varga 's answer ):

 for ($i=0; $i<10000; $i++) { $a=mt_rand(1,50); $b=mt_rand(1,50); $r1 = getcount($a, $b); $r2 = getcount2($b, $b); if ($r1 != $r2) { echo "D'oh!"; } } 

and he will not return anything.

The only drawback is that your code gives a warning when getcount(0, 0) run. Also, the second line in your code ( $min=min($length,$breadth); ) is a bit redundant. You can write the same:

 function getcount($length,$breadth,$count=0){ if($length>$breadth){ $length=$length-$breadth; $count++; return getcount($length,$breadth,$count); } else if($breadth>$length){ $breadth=$breadth-$length; $count++; return getcount($length,$breadth,$count); } else if ($breadth!=0){ $count++; // there is no need to divide two same numbers, right? } return $count; } 
0
source

All Articles