Here's a quick fix in C using the twiddling bit to find min(x, y) . This is a modified version of the @Doug Currie answer and inspired by the answer to Find a question about the minimum positive value :
bool lowestPositive(int a, int b, int* pout) { unsigned x = (a - 1), y = (b - 1); *pout = y + ((x - y) & -(x < y)) + 1; return *pout > 0; }
Example:
#include <assert.h> #include <limits.h> #include <stdio.h> #include <stdbool.h> void T(int a, int b) { int result = 0; printf("%d %d ", a, b); if (lowestPositive(a, b, &result)) printf(": %d\n", result); else printf(" are not positive\n"); } int main(int argc, char *argv[]) { T(5, 6); T(6, 5); T(6, -1); T(-1, -2); T(INT_MIN, INT_MAX); T(INT_MIN, INT_MIN); T(INT_MAX, INT_MIN); T(0, -1); T(0, INT_MIN); T(-1, 0); T(INT_MIN, 0); T(INT_MAX, 0); T(0, INT_MAX); T(0, 0); return 0; }
Output:
5 6 : 5 6 5 : 5 6 -1 : 6 -1 -2 are not positive -2147483648 2147483647 : 2147483647 -2147483648 -2147483648 are not positive 2147483647 -2147483648 : 2147483647 0 -1 are not positive 0 -2147483648 are not positive -1 0 are not positive -2147483648 0 are not positive 2147483647 0 : 2147483647 0 2147483647 : 2147483647 0 0 are not positive
jfs
source share