简单的问题,如何在分割数字时获得所有选项?例如:
24 by 6
返回6, 12, 18, 24
24 by 4
返回4, 8, 12, 16, 20, 24
24 by 5
返回false
我的数据库中有一个数字,例如2,和我的计数器,例如14.这意味着每次我的计数器点击第二个数字时,我想要解雇我的事件。所以我想,如果我有解决方案2,4,6等,并且我的计数器等于其中一个解决方案,我可以解雇我的事件。
答案 0 :(得分:6)
制作起来相当微不足道。
<?php
/**
* @param int $number The beginning number
* @param int $divider The number dividing by
*
* @return array
* @throws Exception In case $number is not divisible by $divider
*/
function get_number_sequence($number, $divider) {
//In case $number is not divisible by $divider, throw an Exception.
if ($number % $divider !== 0) {
throw new Exception("$number is not divisible by $divider");
}
//Return an array from $divider to $number in steps of $divider.
$result = range($divider, $number, $divider);
return $result;
}
/*
* Testing begins
*/
try {
echo "<pre>";
echo implode(", ", get_number_sequence(24, 4)) . PHP_EOL;
echo implode(", ", get_number_sequence(24, 6)) . PHP_EOL;
echo implode(", ", get_number_sequence(24, 5)) . PHP_EOL;
echo "</pre>";
}
catch (Exception $e) {
echo "Invalid: " . $e->getMessage();
}
Exception
。答案 1 :(得分:1)
应该很容易 在X上用Y做模数。如果为0然后在X上用Y进行除法。创建一个循环,该循环将从1运行(X在Y上除以Y)并且输出Y乘以循环计数器
答案 2 :(得分:1)
function findQuotients($number, $divider)
{
$arr = array();
if($number % $divider != 0)
{
//return "false";
}
else
{
$loop = $number / $divider;
//$output="";
for($i = 1; $i <= $loop; $i++)
{
//$output .= $i * $divider. " ";
array_push($arr, $i * $divider);
}
}
return $arr;
}
echo print_r(findQuotients(24, 6));
echo print_r(findQuotients(24, 4));
echo print_r(findQuotients(24, 5));
答案 3 :(得分:1)
function steps($target,$step) {
if (($target % $step) != 0)
return FALSE;
$steps = range($step,$target,$step);
return $steps;
}
$target = 24;
for ($step = 2; $step < 13; ++$step) {
echo '$step = ',$step,PHP_EOL;
$steps = steps($target,$step);
var_dump($steps);
}
答案 4 :(得分:0)
试试这个
$number = 24;
$divider = 6;
if($number % $divider != 0 )
{
return false;
}
$div = $number / $divider;
for($i = 1; $i <= $div; $i++)
{
echo $i*$divider;
}
答案 5 :(得分:0)
以下代码段可以解决问题。这是一个简单的迭代循环,直到$num
&lt; = 0. $num
将被分频器减去,每转$div
的下一个倍数将被存储为“分隔步骤“。
$num = 24;
$div = 4;
if ($num % $div != 0) {
exit('invalid');
}
$divider = array();
for ($i = 1; $num > 0; $i++) {
$divider[] = ($i * $div);
$num -= $div;
}
echo 'in: ' . $num . '<br />';
echo 'div: ' . $div . '<br />';
echo '<pre>';
print_r($divider);
exit;
答案 6 :(得分:0)
根据你的描述,你想要一个数字,然后在给定的结果上你想要白化一个函数:
$num = 6;
$counter = 2;
$solution = 24;
while ($num * $counter) {
$result= $num * $counter;
if ($result = $solution) {
echo $result;
// here would go your event
break;
}
}