Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

一个循环遍历逻辑问题就指教,计算次数判断

问题描述:

定义一个函数用于计算操作,用一个数字去除以多个数字,返回每个数都能除尽的那个数字,并且返回它除以这些数字的结果分别是多少。

代码示例:

function demo($a=null,$b=null)
{
    // $a是一个数字或一个范围数组;
    // $b是一个数组,代表多个除数;
    
    // 难点,如何判断$a里面的某个数字,能同时除尽$b里面的所有数字,并且还要一次性返回$a和$b相除后得到的多个正整数?
}
demo([1000,1600],[4,5,6]);

确实没办法了,被绕了一上午啦,求大神给指点下,目前我能完成计算的是$b确定个数,但实际应用场景是$b可能是多个,$a也可能是其它的数字或范围。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
    function demo($a=null,$b=null)
    {
        $result = array();
        for ($i=$a[0]; $i<=$a[1]; $i++) {
            foreach ($b as $b_key => $b_value) {
                $result[$i][$b_value] = $i / $b_value;  //假设b中所有都能整除 , 先把值存起来
                if ($i % $b_value != 0) {
                    unset($result[$i]); // 一旦b中有一个数字不满足, 例如 1000 / 7 , 那就跳出循环, 移除 $result['1000']
                    break;
                }
            }
        }
        return $result;
    }
    print_r(demo([1000,1600],[4,5,6]));

//结果 (浏览器输出我就不调格式了)
//结果数组中 key $a范围内满足的数, value是数组(这个数组中key是b中的值, value是整除的结果)
//其他情况你自己再判断吧(比如 $a 和 $b 是一个数字)


Array
(
    [1020] => Array
        (
            [4] => 255
            [5] => 204
            [6] => 170
        )

    [1080] => Array
        (
            [4] => 270
            [5] => 216
            [6] => 180
        )

    [1140] => Array
        (
            [4] => 285
            [5] => 228
            [6] => 190
        )

    [1200] => Array
        (
            [4] => 300
            [5] => 240
            [6] => 200
        )

    [1260] => Array
        (
            [4] => 315
            [5] => 252
            [6] => 210
        )

    [1320] => Array
        (
            [4] => 330
            [5] => 264
            [6] => 220
        )

    [1380] => Array
        (
            [4] => 345
            [5] => 276
            [6] => 230
        )

    [1440] => Array
        (
            [4] => 360
            [5] => 288
            [6] => 240
        )

    [1500] => Array
        (
            [4] => 375
            [5] => 300
            [6] => 250
        )

    [1560] => Array
        (
            [4] => 390
            [5] => 312
            [6] => 260
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...