猿问

返回所有整数除数或返回字符串 '(integer) is prime' 如果它是素数的函数

嘿到目前为止我得到的解决方案给了我一些整数的预期结果,但不满足测试用例,(codewars https://www.codewars.com/kata/find-the-divisors/train/php)


function divisors($integer) {


    $array = [];


    if($integer<=1)

        return false;


    for($i = 2 ; $i <= sqrt($integer) ; $i++){

        if($integer% $i == 0){

            array_push($array,$i);

        }     

    }


    if (empty($array)){

        return $integer. " is prime";

    }else{

        return implode( ", ", $array );

    }

}

任何帮助表示赞赏,现在我收到以下错误


3' does not match expected type "array"


蓝山帝景
浏览 103回答 2
2回答

慕丝7291255

以下解决方案,通过了所有测试用例function divisors($integer) {&nbsp; &nbsp; $array = [];&nbsp; &nbsp; &nbsp;if($integer >1)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; for($i = 2 ; $i < $integer ; $i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if($integer% $i == 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $array[] = $i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (empty($array)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $integer. " is prime";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; return $array;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }//close if($integer>1)&nbsp; }//END function divisors

猛跑小猪

您将很快终止循环,只需查看这些数字的 sqrt() 是什么。而是在整数的一半处终止循环function divisors($integer) {&nbsp; &nbsp; $array = [];&nbsp; &nbsp; if($integer<=1)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; $end = $integer / 2;&nbsp; &nbsp; for($i = 2 ; $i <= $end; $i++){&nbsp; &nbsp; &nbsp; &nbsp; if($integer % $i == 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $array[] = $i;&nbsp; &nbsp; &nbsp; // more efficient than array_push if youare just pushing on thing&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; if (empty($array)){&nbsp; &nbsp; &nbsp; &nbsp; return $integer. " is prime";&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; return $array;&nbsp; &nbsp; }}结果2, 3, 4, 6513 is prime
随时随地看视频慕课网APP
我要回答