Create a Fraction type with add and multiply functions that always return the fraction in lowest terms, with the sign in the numerator.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
long num, den;
} Fraction;
static long gcd(long a, long b) {
a = labs(a);
b = labs(b);
while (b != 0) {
long t = a % b;
a = b;
b = t;
}
return a;
}
static Fraction make(long num, long den) {
if (den < 0) { /* keep the sign in the numerator */
num = -num;
den = -den;
}
long g = gcd(num, den);
return (Fraction){num / g, den / g};
}
Fraction add(Fraction a, Fraction b) { return make(a.num * b.den + b.num * a.den, a.den * b.den); }
Fraction mul(Fraction a, Fraction b) { return make(a.num * b.num, a.den * b.den); }
int main(void) {
Fraction half = {1, 2}, third = {1, 3}, f23 = {2, 3}, f34 = {3, 4}, neg = {-3, 4};
Fraction r1 = add(half, third), r2 = mul(f23, f34), r3 = add(half, neg);
printf("%ld/%ld %ld/%ld %ld/%ld\n", r1.num, r1.den, r2.num, r2.den, r3.num, r3.den);
return 0;
}
5/6 1/2 -1/4
Every result passes through make(), which normalises the sign and divides by the gcd, so 6/12 becomes 1/2. Small typedef'd structs returned by value make the API feel like built-in arithmetic.