I have this code:


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?

  • 1
    $\begingroup$ 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... $\endgroup$
    – entrelac
    Jul 26, 2016 at 18:23
  • $\begingroup$ Thanks, but I don't want to resort to numerical methods to compute a max :) $\endgroup$
    – gurghet
    Jul 26, 2016 at 19:22

1 Answer 1


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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .