-3

It can be regarding any programming language.

For example in PHP:

if($x > 2) { $x=2; } 

Is there any way to not use a condition, but use some mathematical expression to reach the same result?

Sergey Kravchenko
  • 957
  • 1
  • 8
  • 21

1 Answers1

0

I found the answer

$maxval = 2;

$x = $maxval - (abs($maxval - $x) + $maxval - $x) / 2;

so if $x > $maxval, this expression (abs($maxval - $x) + $maxval - $x) / 2; becomes 0 and $x becomes equal to $maxval else this expression is equal to $maxval - $x, and the whole equation becomes $x = $x

but the shortest solution is

$x = min($x, 2);
Sergey Kravchenko
  • 957
  • 1
  • 8
  • 21