Math Fundamentals18 sections · 814 units
Open in Course

Fraction Addition - Implementation

The pseudocode

Here is the core addition and simplification logic:


function addFractions(fractions)
    num := 0
    denom := 1
    for each (a, b) in fractions
        num := num * b + a * denom
        denom := denom * b
        g := gcd(abs(num), denom)
        num := num / g
        denom := denom / g
    return num + "/" + denom

function gcd(a, b)
    while b != 0
        temp := b
        b := a mod b
        a := temp
    return a

Time: O(nlogM)O(n \log M) where nn is the number of fractions and MM is the max denominator. Space: O(1)O(1) for the math operations.