douzhanrun0497 2014-04-23 10:40
浏览 44
已采纳

计算矩形的平方数

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?

  • 写回答

2条回答 默认 最新

  • dongtou2016 2014-04-23 10:56
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析