【发布时间】:2011-01-06 14:57:10
【问题描述】:
我想检查一个数字是否能被 6 整除,如果不能被 6 整除,我需要增加它直到它可以被整除。
我该怎么做?
【问题讨论】:
我想检查一个数字是否能被 6 整除,如果不能被 6 整除,我需要增加它直到它可以被整除。
我该怎么做?
【问题讨论】:
使用Mod %(模数)运算符
if ($x % 6 == 0) return 1;
function nearest_multiple_of_6($x) {
if ($x % 6 == 0) return $x;
return (($x / 6) + 1) * 6;
}
【讨论】:
【讨论】:
只需运行一个 while 循环,它将继续循环(并增加数字),直到数字可以被 6 整除。
while ($number % 6 != 0) {
$number++;
}
【讨论】:
对于微优化狂:
if ($num % 6 != 0)
$num += 6 - $num % 6;
更多对% 的评估,但更少的分支/循环。 :-P
【讨论】:
$num += (6-$num%6)%6;
不需要while循环!模 (%) 返回除法的余数。 IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 可以被 6 整除。
【讨论】:
你为什么不使用Modulus Operator?
试试这个:
while ($s % 6 != 0) $s++;
或者这就是你的意思?
<?
$s= <some_number>;
$k= $s % 6;
if($k !=0) $s=$s+6-$k;
?>
【讨论】:
if ($variable % 6 == 0) {
echo 'This number is divisible by 6.';
}:
能被 6 整除:
$variable += (6 - ($variable % 6)) % 6; // faster than while for large divisors
【讨论】:
if ($number % 6 != 0) {
$number += 6 - ($number % 6);
}
modulus 运算符给出除法的余数,因此 $number % 6 是除以 6 时的余数。这比循环并不断重新检查要快。
如果减少是可以接受的,那么这会更快:
$number -= $number % 6;
【讨论】:
if( 6 % $number != 0) {}
result = initial number + (6 - initial number % 6)
【讨论】:
假设$foo 是一个整数:
$answer = (int) (floor(($foo + 5) / 6) * 6)
【讨论】:
我看到其他一些答案调用模数两次。
我的偏好是不要让 php 多次做同样的事情。出于这个原因,我缓存了其余部分。
其他开发人员可能更愿意不生成额外的全局变量或有其他理由使用两次模运算符。
代码:(Demo)
$factor = 6;
for($x = 0; $x < 10; ++$x){ // battery of 10 tests
$number = rand( 0 , 100 );
echo "Number: $number Becomes: ";
if( $remainder = $number % $factor ) { // if not zero
$number += $factor - $remainder; // use cached $remainder instead of calculating again
}
echo "$number\n";
}
可能的输出:
Number: 80 Becomes: 84
Number: 57 Becomes: 60
Number: 94 Becomes: 96
Number: 48 Becomes: 48
Number: 80 Becomes: 84
Number: 36 Becomes: 36
Number: 17 Becomes: 18
Number: 41 Becomes: 42
Number: 3 Becomes: 6
Number: 64 Becomes: 66
【讨论】: