WMI
WMI

Reputation: 159

Highest multiplication with multiple and max number set

Not quite sure what to set this title as, or what to even search for. So I'll just ask the question and hope I don't get too many downvotes.

I'm trying to find the easiest way to find the highest possible number based on two fixed numbers.

For example:

The most I can multiply by is, say, 18 (first number). But not going over the resulted number, say 100 (second number).

2 x 18 = 36

5 x 18 = 90

But if the first number is a higher number, the second number would need to be less than 18, like so:

11 x 9 = 99

16 x 6 = 96

Here I would go with 11, because even though the second number is only 9, the outcome is the highest. The second number could be anything as long as it's 18 or lower. The first number can be anything, as long as the answer remains below 100. Get what I mean?

So my question is, how would write this in php without having to use switches, if/then statements, or a bunch of loops? Is there some math operator I don't know about that handles this sort of thing?

Thanks.

Edit:

The code that I use now is:

function doMath($cost, $max, $multiplier) {
    do {
      $temp = $cost * $multiplier;
      if ($temp > $max) { --$multiplier; }
    } while ($temp > $max);    
    return array($cost, $temp, $multiplier);
}

If we look at the 11 * 9 = 99 example,

$result = doMath(11, 100, 18);

Would return,

$cost = 11, $temp = 99, $multiplier = 9

Was hoping there was an easier way so that I wouldn't need to use a loop, being as how there are a lot of numbers I need to check.

Upvotes: 0

Views: 335

Answers (1)

Cimbali
Cimbali

Reputation: 11405

If I understood you right, you are looking for the floor function, combining it with the min function.

Both a bigger number c and a smaller number a are part of the problem, and you want to find a number b in the range [0, m] such that a * b is maximal while staying smaller (strictly) than c.

In your example, 100/18 = 5.55555, so that means that 18*5 is smaller than 100, and 18*6 is bigger than 100.

Since floor gets you the integral part of a floating point number, $b = floor($c/$a) does what you want. When a divides c (that is, c/a is an integer already), you get a * b == c.

Now b may be outside of [0,m] so we want to take the smallest of b and m :

  • if b is bigger than m, we are limited by m,
  • and if m is bigger than b, we are limited by a * b <= c.

So in the end, your function should be :

function doMath($cost, $max, $multiplier)
{
    $div = min($multiplier, floor($max/$cost));
    return array($cost, $div * $cost, $div);
}

Upvotes: 1

Related Questions