* Deterministic approximate division. * Cancels out division errors stemming from the integer nature of the division over multiple runs. * @param a Dividend. * @param b Divisor. * @return a/b or (a/b)+1. */
| 20 | * @return a/b or (a/b)+1. |
| 21 | */ |
| 22 | int DivideApprox(int a, int b) |
| 23 | { |
| 24 | int random_like = ((a + b) * (a - b)) % b; |
| 25 | |
| 26 | int remainder = a % b; |
| 27 | |
| 28 | int ret = a / b; |
| 29 | if (abs(random_like) < abs(remainder)) { |
| 30 | ret += ((a < 0) ^ (b < 0)) ? -1 : 1; |
| 31 | } |
| 32 | |
| 33 | return ret; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Compute the integer square root. |
no test coverage detected