如何检查数字是否是输入的倍数 - PHP

How can I check if a number is a multiple of the input - PHP

我要构建的是一个接受输入数字并检查后面的数字是否是该数字的倍数的函数。

function checkIfMult($input,$toBeChecked){
   // some logic
}

示例:

checkIfMult(2,4) // true
checkIfMult(2,6) // true
checkIfMult(2,7) // false

checkIfMult(3,6) // true
checkIfMult(3,9) // true
checkIfMult(3,10) // false

我的第一直觉是使用数组

$tableOf2 = [2,4,6,8,10,12,14,16,18]

但是像这样的调用是非常不切实际的:

checkIfMult(6,34234215)

我如何检查某项是否是输入的倍数?

使用 % 运算符。

模运算符除以数字并 returns 余数。

在数学中,倍数表示余数等于 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

你可以取模 % 比如:

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 );
}

这跟结果

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

您可以使用取模运算符,如果结果为 0,则函数应该 return 为真。取模运算符 (%) 执行除法,return 求余数。

http://php.net/manual/en/language.operators.arithmetic.php

您可以使用 % 运算符

function check($a,$b){
   if($b % $a > 0){
     return 0;
   }
   else{
    return 1;
   }
}

或者,您也可以将$tobechecked除以$input,然后使用floor函数检查是否有余数。

if(is_int($result))
 { echo "It is a multiple";
    }
 else
 { echo "It isn't a multiple"; }