我怎样才能找到一个数能被1整除的最小数是多少?
例如,我有一个数字33。我知道它可以被3整除的最小数字是3,但是我想知道如何使用PHP来解决这个问题。
发布于 2015-06-16 09:02:49
使用简单的for循环,带有'%‘运算符:
<?php
$number = 33;
for($i=2; $i <= $number; ++$i)
{
if($number % $i == 0)
{
echo 'lowest number is '.$i;
break;
}
}
?>发布于 2015-06-16 09:07:13
您可以使用如下方法:
/**
* 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)); // 2https://stackoverflow.com/questions/30857257
复制相似问题