# Simplify non-linear but simple expression with max and min

I have this code:

max(n+1,min(numPages+n-4,currentPage+n-2))


which is equivalent to the expression

$\max\{n+1, \min\{N+n-4, m+n-2\}\}$

$0<m<N, 0\le n\le5$

Is there any neat/weird trick to simplify it? Even only w.r.t. a computational standpoint?

• Finding the maximum and minimum are already very straightforward operations. If you're looking for a formal definition, here's one: $$\max\{a,b\}=\lim_{n\rightarrow\infty} (a^n+b^n)^{1/n}$$ $$\min\{a,b\}=a+b-\max\{a,b\}$$ but this makes things more costly... Jul 26, 2016 at 18:23
• Thanks, but I don't want to resort to numerical methods to compute a max :) Jul 26, 2016 at 19:22

though it hardly matters to have 2-3 more or less additions(or any basic arithmetic operations, as at hardware level it's very fast, so definitely other components of a code make the bottleneck for efficiency, but as you have asked:

$\max\{n+1, \min\{N+n-4, m+n-2\}\}$

assuming all are positive numbers (as it shows, they are page numbers etc),

it is equivalent to

       n + max{1, min{N-4, m-2}}


// by doing this you are avoiding 2 extra additions during evaluation.

Now in all cases you can write

       n+1 + min{N-5, m-3}


note that you don't have to check whether $min\{N-5, m-3\}$ > 0 if you constrain N & m accordingly.

any other optimization I could think of, is subjective to the implementation and scenario you are dealing with.

So overall we have saved 1 addition and 1 comparison.

• Clever! Although I don't know a program that interprets negative number as 0 when unsigned int Jul 26, 2016 at 19:16
• I added some constraints, I'm checking if that makes any difference. Jul 26, 2016 at 19:24
• @gurghet sorry for the error. Edited. Jul 27, 2016 at 9:23