Use the Euclidean algorithm with floor quotient and nonnegative remainder, including for a negative numerator:For , Euclidean division gives with . If , the singleton
PROCEDURE rat2cf(n, d: INTEGER): fraction;
VAR q, r: INTEGER; p: fraction;
BEGIN
q := n DIV d; r := n MOD d;
NEW(p); p.head := q; p.tail := NIL;
IF r # 0 THEN p.tail := rat2cf(d, r) END;
RETURN p
END rat2cf;[q] is exact. Otherwiseso the recursive tail represents . Its numerator is positive and greater than its denominator, so every tail head is a positive integer. The new denominator is strictly smaller than , proving algorithm termination by descent through the positive integers.The returned list represents exactly . For example gives
[-3,1,2]; truncating negative division toward zero would violate the required positivity of the tail. There are Euclidean algorithm steps, with output allocation and recursive stack depth linear in the number of generated nodes. Articles by others on the same topic
There are currently no matching articles.