skip to Main Content

Is there a math functon in PHP that would provide safe division without fractions/decimal numbers? Meaning that it would "distribute" the amount as equally as possible, but only in whole numbers.

Some examples:

10/3 = [4, 3, 3]

11/3 = [4, 4, 3]

50/2 = [25, 25]

51/2 = [26, 25]

40/5 = [8, 8, 8, 8, 8]

40/3 = [14, 13, 13]

Meaning that 40/3 should give me three values 14, 13 and 13

2

Answers


  1. There is no such thing out of stock. You may write your own function for it.

    function sdiv($dividend, $divisor) {
      $q = $dividend / $divisor;
      return [ceil($q), round($q), floor($q)];
    }
    
    list($ceil, $round, $floor) = sdiv(10, 3);
    
    Login or Signup to reply.
  2. Since there’s no working solution yet, here’s one:

    The question seems to ask to split (partition) an integer number s into a set of n numbers that are either q1 = ceil(s/n) or q2 = floor(s/n)
    Since q1 - q2 = 1, that split can be generated by the formula:

    q1 * (s - q2 * n) + q2 * (q1 * n - s) = (q1 - q2) * s = s,
    

    that is

    s = n1 * q1 + n2 * q2,
    

    with n1 = s - q2 * n, n2 = q1 * n - s, and n1 + n2 = (q1 - q2) * n = n

    Php function:

    function splitInt($s, $n) {
      $q = $s / $n;
      $q1 = ceil($q);
      $q2 = floor($q);
      $n1 =  $q1 * $n - $s;
      // the result is [$n1 x q1, ($n - $n1) x $q2]
      return array_pad(array_fill(0, $n1, $q1), $n, $q2);
    }
    

    Example:

    $res = splitInt(100, 7);
    echo json_encode($res) . "n";
    $sum = array_sum($res);
    $count = count($res);
    echo "count = $count   sum = $sumnn";
    

    gives

    [15,15,14,14,14,14,14]
    count = 7   sum = 100
    

    More examples in sandbox.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search