0

Any programmer can explain how to express this code in math terms?

public static int px32(int p){
    int h = 0;
    for (int i = 0; i < p; i = i + 32) { h++; }
    return h;
}
Rócherz
  • 3,976
  • Where did you come across this problem? And what do you think? Have you tried for a few different values of $p$ and seen what you get? Can you describe the result in words? – Arthur Apr 26 '18 at 18:58
  • I know it's a simple division, but I'm aiming to increase the performance of a renderer (2D tile based).

    I tried if(p <= 0){ return 0; } return p / 32; but did not give the same result.

    – Jonathan Costa Apr 26 '18 at 19:02
  • $#{ i \in \mathbb{N} : i < p \land \exists k \in \mathbb{N}, i = 32k } = #{ k \in \mathbb{N} : k < \frac{p}{32} } = \lfloor\frac{p+31}{32}\rfloor$ (assume $p \ge 0$). – achille hui Apr 26 '18 at 19:02
  • Still necessary use if(p <= 0) { return 0; }

    Any way for no need use?

    – Jonathan Costa Apr 26 '18 at 19:15
  • $\text{return (p<0) ? 0 : ((p+31)>>5);}$ this is essentially achille hui's retranslated code. – zwim Apr 26 '18 at 19:22
  • zwim, it works. Retranslate the Rócherz with max in answer below, please. xD – Jonathan Costa Apr 26 '18 at 19:25
  • It is the same, calculating ceil(x) value is the same as calculating floor(x+31) value. And shifting by $5$ is the same as dividing by $32$. I don't think there is much more efficient than that, considering that the compilo will much probably also optimize the ? : ternary operator. – zwim Apr 26 '18 at 19:30

1 Answers1

4

Summarizing the thread so far, the code above (along with a if(p <= 0) { return 0; }) computes \begin{matrix} &{\rm R\acute{o}cherz} &\text{achille hui}\\ h={}&\left\lceil\dfrac{\max\{0,p\}}{32}\right\rceil &=\left\lfloor\dfrac{\max\{0,p\}+31}{32}\right\rfloor & \qquad \text{for } p \in \mathbb{Z}. \end{matrix} However, since $32 =2^5$ is a power of $2$, perhaps the fastest way to compute $h$ is (zwim):

return (p<0) ? 0 : ((p+31)>>5);.

Rócherz
  • 3,976