Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neatest / Fastest Algorithm for Smallest Positive Number

Simple question - In c++, what's the neatest way of getting which of two numbers (u0 and u1) is the smallest positive number? (that's still efficient)

Every way I try it involves big if statements or complicated conditional statements.

Thanks, Dan

Here's a simple example:

bool lowestPositive(int a, int b, int& result)
{
    //checking code
    result = b;
    return true;
}


lowestPositive(5, 6, result);
like image 442
Dan Avatar asked Dec 26 '08 15:12

Dan


3 Answers

If the values are represented in twos complement, then

result = ((unsigned )a < (unsigned )b) ? a : b;

will work since negative values in twos complement are larger, when treated as unsigned, than positive values. As with Jeff's answer, this assumes at least one of the values is positive.

return result >= 0;
like image 151
Doug Currie Avatar answered Nov 07 '22 21:11

Doug Currie


I prefer clarity over compactness:

bool lowestPositive( int a, int b, int& result )
{
   if (a > 0 && a <= b) // a is positive and smaller than or equal to b
      result = a;
   else if (b > 0) // b is positive and either smaller than a or a is negative
      result = b;
   else
      result = a; // at least b is negative, we might not have an answer

   return result > 0;  // zero is not positive
}
like image 31
tvanfosson Avatar answered Nov 07 '22 19:11

tvanfosson


Might get me modded down, but just for kicks, here is the result without any comparisons, because comparisons are for whimps. :-)

bool lowestPositive(int u, int v, int& result)
{
  result = (u + v - abs(u - v))/2;
  return (bool) result - (u + v + abs(u - v)) / 2;
}

Note: Fails if (u + v) > max_int. At least one number must be positive for the return code to be correct. Also kudos to polythinker's solution :)

like image 39
mstrobl Avatar answered Nov 07 '22 21:11

mstrobl