Here is one way that works for positive integers:
bool greaterPositiveFraction(int a,int b,int c,int d); bool greaterOrEqualPositiveFraction(int a,int b,int c,int d) { if (b == 0) return true; if (d == 0) return false; if (a/b > c/d) return true; if (a/b < c/d) return false; return !greaterPositiveFraction(b,a%b,d,c%d); } bool greaterPositiveFraction(int a,int b,int c,int d) { if (d == 0) return false; if (b == 0) return true; if (a/b > c/d) return true; if (a/b < c/d) return false; return !greaterOrEqualFraction(b,a%b,d,c%d); }
The idea is that if integer division is less or more, then you know the answer. It is difficult if integer division gives you the same result. In this case, you can simply use the remainder and see if there is% b / b> c% d / d. However, we know that a% b / b> c% d / d if b / (a% b) d / (c% d), so we can simply reverse the problem and try it again.
Integer division with residuals of negative values ββis a bit more random, but they can be easily handled on occasion:
bool greaterFraction(int a,int b,int c,int d) { if (b<0) { b = -b; a = -a; } if (d<0) { d = -d; c = -c; } if (a<0 && c<0) return greaterPositiveFraction(-c,d,-a,b); if (a<0) return false; if (c<0) return true; return greaterPositiveFraction(a,b,c,d); }
Vaughn cato
source share