Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate number of squares from a rectangle

Tags:

php

I'm working on some PHP code but I'm stuck with a logic. I need to find out the number of squares from a rectangle.

I'm unable to 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 how it doesn't pass all the use cases. And i do not know on which use cases, it fails?

like image 465
Pruthvi Raj Nadimpalli Avatar asked Apr 23 '14 10:04

Pruthvi Raj Nadimpalli


People also ask

How many squares can be cut from a rectangle?

For example: If the rectangle is of size 6×9. We can cut it into 54 squares of size 1×1, 0 of size 2×2, 6 of size 3×3, 0 of size 4×4, 0 of size 5×5 and 0 of size 6×6.

How many squares are in a 3x4 rectangle?

a 3x4 grid has 12 1x1 (3 * 4) squares 6 2x2 (2 * 3) squares and 2 3x3 squares = 20.


1 Answers

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

It 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
like image 144
Balázs Varga Avatar answered Oct 16 '22 05:10

Balázs Varga