Mathematically Find Max Value without Conditional Comparison

前端 未结 14 586
暗喜
暗喜 2020-12-03 03:39

----------Updated ------------

codymanix and moonshadow have been a big help thus far. I was able to solve my problem using the equations and instead of using right

14条回答
  •  [愿得一人]
    2020-12-03 03:47

    If A is always greater than B .. [ we can use] .. MAX = (A - B) + B;

    No need. Just use: int maxA(int A, int B){ return A;}

    (1) If conditionals are allowed you do max = a>b ? a : b.

    (2) Any other method either use a defined set of numbers or rely on the implicit conditional checks.

    (2a) max = a-((a-b)&((a-b)>>31)) this is neat, but it only works if you use 32 bit numbers. You can expand it arbitrary large number N, but the method will fail if you try to find max(N-1, N+1). This algorithm works for finite state automata, but not a Turing machine.

    (2b) Magnitude |a-b| is a condition |a-b| = a-b>0 a-b : b-a

    What about:

    Square root is also a condition. Whenever c>0 and c^2 = d we have second solution -c, because (-c)^2 = (-1)^2*c^2 = 1*c^2 = d. Square root returns the greatest in the pair. I comes with a build in int max(int c1, int c2){return max(c1, c2);}

    Without comparison operator math is very symmetric as well as limited in power. Positive and negative numbers cannot be distinguished without if of some sort.

提交回复
热议问题