checking if a number is divisible by 6 PHP

前端 未结 11 1698
不思量自难忘°
不思量自难忘° 2020-12-13 02:15

I want to check if a number is divisible by 6 and if not I need to increase it until it becomes divisible.

how can I do that ?

相关标签:
11条回答
  • 2020-12-13 02:35

    Why don't you use the Modulus Operator?

    Try this:

    while ($s % 6 != 0) $s++;
    

    Or is this what you meant?

    <?
    
     $s= <some_number>;
     $k= $s % 6;
    
     if($k !=0)    $s=$s+6-$k;
    ?>
    
    0 讨论(0)
  • 2020-12-13 02:36

    So you want the next multiple of 6, is that it?

    You can divide your number by 6, then ceil it, and multiply it again:

    $answer = ceil($foo / 6) * 6;
    
    0 讨论(0)
  • 2020-12-13 02:38

    Simply run a while loop that will continue to loop (and increase the number) until the number is divisible by 6.

    while ($number % 6 != 0) {
        $number++;
    }
    
    0 讨论(0)
  • 2020-12-13 02:41

    For micro-optimisation freaks:

    if ($num % 6 != 0)
        $num += 6 - $num % 6;
    

    More evaluations of %, but less branching/looping. :-P

    0 讨论(0)
  • 2020-12-13 02:42
    if ($number % 6 != 0) {
      $number += 6 - ($number % 6);
    }
    

    The modulus operator gives the remainder of the division, so $number % 6 is the amount left over when dividing by 6. This will be faster than doing a loop and continually rechecking.

    If decreasing is acceptable then this is even faster:

    $number -= $number % 6;
    
    0 讨论(0)
  • 2020-12-13 02:45
    $num += (6-$num%6)%6;
    

    no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.

    0 讨论(0)
提交回复
热议问题