checking if a number is divisible by 6 PHP

前端 未结 11 1731
不思量自难忘°
不思量自难忘° 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:46

    I see some of the other answers calling the modulo twice.

    My preference is not to ask php to do the same thing more than once. For this reason, I cache the remainder.

    Other devs may prefer to not generate the extra global variable or have other justifications for using modulo operator twice.

    Code: (Demo)

    $factor = 6;
    for($x = 0; $x < 10; ++$x){  // battery of 10 tests
        $number = rand( 0 , 100 );
        echo "Number: $number Becomes: ";
        if( $remainder = $number % $factor ) {  // if not zero
            $number += $factor - $remainder;  // use cached $remainder instead of calculating again
        }
        echo "$number\n";
    }
    

    Possible Output:

    Number: 80 Becomes: 84
    Number: 57 Becomes: 60
    Number: 94 Becomes: 96
    Number: 48 Becomes: 48
    Number: 80 Becomes: 84
    Number: 36 Becomes: 36
    Number: 17 Becomes: 18
    Number: 41 Becomes: 42
    Number: 3 Becomes: 6
    Number: 64 Becomes: 66
    

提交回复
热议问题