G
G
GRO242021-06-05 13:29:34
PHP
GRO24, 2021-06-05 13:29:34

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;

How would you do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Adamos, 2021-06-05
@GRO24

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

T
Talgat_Sat, 2021-06-05
@Talgat_Sat

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 ) );

The logarithm of a number x is a number such that when you take the base of that logarithm to the logarithm, you get x. i.e. instead of a cycle, you can simply take the logarithm.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question