如何找到数字可被1除以的最小数字?
例如,我有33号。我知道它可被整除的最小数字是3,但我想知道如何用PHP来解决这个问题。
答案 0 :(得分:6)
使用简单的for循环,使用'%'操作者:
<?php
$number = 33;
for($i=2; $i <= $number; ++$i)
{
if($number % $i == 0)
{
echo 'lowest number is '.$i;
break;
}
}
?>
答案 1 :(得分:3)
您可以使用以下方法:
/**
* Return the lowest whole divisor for the passed in number, greater than one
* @param int $number
* @return int|false The lowest divisor (above one). Last resort is that the return
* value will be the number passed in, or bool false if you passed
* in 1
*/
function lowestWholeDivisor($number)
{
for ($i = 2; $i <= $number; $i++) {
$calc = $number / $i;
// is_int() will return false if the input is a float, e.g. has a decimal point
if (is_int($calc)) {
return $i;
}
}
return false;
}
像这样使用:
var_dump(lowestWholeDivisor(33)); // 3
var_dump(lowestWholeDivisor(1)); // false
var_dump(lowestWholeDivisor(2)); // 2
var_dump(lowestWholeDivisor(3)); // 3
var_dump(lowestWholeDivisor(4)); // 2
var_dump(lowestWholeDivisor(5)); // 5
var_dump(lowestWholeDivisor(6)); // 2