# Routines to calculate the continued fraction expansion of # a rational number. # cFrac( r ) returns an integer list [a_1,a_2,...,a_n] which # is the continued fraction expansion of r in which all # terms have the same sign as r. integerPart := function( r ) # Assumes that r > 0. # Returns the greatest integer less than or equal to r. local p, q, integerQuotient; p := NumeratorRat( r ); q := DenominatorRat( r ); return QuoInt( p, q); end; modZPart := function( r ) # Assumes that r > 0. return r - integerPart( r ); end; cFracExpansion := function( r ) # Assumes that r > 0. local expansion, remainder, reciprocal; expansion := []; Add( expansion, integerPart( r ) ); remainder := modZPart(r); while( remainder > 0 ) do reciprocal := 1/remainder; Add( expansion, integerPart( reciprocal ) ); remainder := modZPart( reciprocal ); od; return expansion; end; cFrac := function( r ) local expansion; expansion := []; if r = 0 then Add( expansion, 0 ); elif r > 0 then expansion := cFracExpansion( r ); else expansion := -cFracExpansion( -r ); fi; return expansion; end;