data-structures · intermediate · ~15 min

Compare fractions

Use a typedef'd struct and compare without floating point.

Challenge

Compare two fractions without converting them to floating point.

Task

Define typedef struct { int num, den; } Frac; and implement int frac_cmp(Frac a, Frac b) that returns -1 if a < b, 0 if a == b, and 1 if a > b. Compare by cross-multiplication, not division.

Input

Two Frac values passed by value. Each has int fields num (numerator) and den (denominator); denominators are positive.

Output

int: -1, 0, or 1.

Example

a={1,2}, b={2,4}   ->   0    (equal)
a={1,3}, b={1,2}   ->   -1   (a < b)
a={3,4}, b={1,2}   ->   1    (a > b)

Edge cases

  • Different representations of the same value (1/2 vs 2/4) compare equal.
  • Use a wide type (long) for the cross-products to avoid int overflow.

Rules

  • Do not use floating point or division; compare a.num*b.den against b.num*a.den.

Input format

Two Frac values (each int num, den, with positive den), by value.

Output format

int: -1, 0, or 1 for a<b, a==b, a>b.

Constraints

No floating point. Cross-multiply using long to avoid overflow.

Starter code

typedef struct { int num, den; } Frac;

int frac_cmp(Frac a, Frac b) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.