如何检查数字是否是输入的倍数 - PHP
What I am trying to build is a function that takes an input number and checks if the following number is a multiple of that number.
function checkIfMult($input,$toBeChecked){
// some logic
}
example:
checkIfMult(2,4) // true
checkIfMult(2,6) // true
checkIfMult(2,7) // false
checkIfMult(3,6) // true
checkIfMult(3,9) // true
checkIfMult(3,10) // false
My first instinct was to use arrays
$tableOf2 = [2,4,6,8,10,12,14,16,18]
But then a call like this would be highly unpractical:
checkIfMult(6,34234215)
How can I check to see if something is a multiple of the input?
我想要构建的是一个函数,它接受一个输入数字并检查以下数字是否是 那个号码。 p>
function checkIfMult($ input,$ toBeChecked){
// some logic
}
code> pre>
示例: p>
checkIfMult(2,4)// true
checkIfMult(2,6)// true
checkIfMult(2,7)// false
checkIfMult(3,6)// true
checkIfMult(3,9)// true
checkIfMult(3,10)// false
code> pre>
我的第一直觉 是使用数组 p>
$ tableOf2 = [2,4,6,8,10,12,14,16,18]
code> pre>
但是这样的调用非常不实用: p>
checkIfMult(6,34234215)
code> pre>
如何检查某些内容是否是输入的倍数? p>
div>
Use the % operator.
The Modulo operator divides the numbers and returns the remainder.
In math, a multiple means that the remainder equals 0.
function checkIfMult($input,$toBeChecked){
return $toBeChecked % $input === 0;
}
function checkIfMult($input, $toBeChecked){
console.log('checkIfMult(' + $input +',' + $toBeChecked + ')', $toBeChecked % $input === 0);
return $toBeChecked % $input === 0;
}
checkIfMult(2,4) // true
checkIfMult(2,6) // true
checkIfMult(2,7) // false
checkIfMult(3,6) // true
checkIfMult(3,9) // true
checkIfMult(3,10) // false
</div>
You can modulo %
Like:
In computing, the
modulo
operation finds the remainder after division of one number by another (sometimes called modulus).
function checkIfMult($input,$toBeChecked){
return !( $toBeChecked % $input );
}
This follow the result
echo "<br />" . checkIfMult(2,4); // true
echo "<br />" . checkIfMult(2,6); // true
echo "<br />" . checkIfMult(2,7); // false
echo "<br />" . checkIfMult(3,6); // true
echo "<br />" . checkIfMult(3,9); // true
echo "<br />" . checkIfMult(3,10); // false
You can use the modulus operator, if the result is 0 then the function should return true. The modulus operator (%) performs a division and returns the remainder.
You can use % operator
function check($a,$b){
if($b % $a > 0){
return 0;
}
else{
return 1;
}
}
Alternatively, You can also divide the $tobechecked by $input and check if there is a remainder by using the floor function.
if(is_int($result))
{ echo "It is a multiple";
}
else
{ echo "It isn't a multiple"; }