Answer the question
In order to leave comments, you need to log in
How to round a number down a multiple of a number?
I am sure that my solution is not the most elegant.
There is the number of participants: let's say 187.
There is the number of winners: for example, 5.
I need to round the number of participants so that when dividing this number constantly by 2, I get the number 5 as a result
. In this example, the number 160 is obtained; (160/2=80/2=40/2=20/2=10/2=5) - I hope I didn't confuse here.
I solved it with a loop:
$input = 187;
$output = 5;
while (true) {
if($output > $input):
$output = $output/2;
break;
endif;
$output = 2*$output;
}
echo $output;
Answer the question
In order to leave comments, you need to log in
Bisection could lead to more computer thoughts.
Algorithm for finding such a number for N participants with X number of winners:
Divide N evenly by X, leave only the most significant bit in the result, multiply this by X.
187 / 5 = 37 = 100101b
100000b * 5 = 160
It's easier to do mathematically,
<?php
$input = 187;
$output = 5;
$buf=log ( intdiv($input, $output ),2 );
echo(round ( $buf, 0 , PHP_ROUND_HALF_UP ) );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question