'Subject: The continued fraction algorithm.
'         Simplify ratios and express decimals as common fractions.
'Author : Sjoerd.J.Schaper
'Date   : 28-12-2003
'Code   : QuickBasic, PDS, VBdos
REM $LANG: "qb"
REM $INCLUDE: 'largeint.bi'
CONST n = 0, d = 1, a = 2, qx = 3
CONST p0 = 4, p1 = 5, q0 = 6, q1 = 7
t = LargeInit(q1, "rational")
DIM g AS STRING
CLS : tim# = TIMER: lin = 8

begin:
LOCATE 1, 1
PRINT "   +------------------------------+"
PRINT "   |  input                       |"
PRINT "   |  numerator and denominator,  |"
PRINT "   |  0 to exit.                  |"
PRINT "   |                              |"
PRINT "   +------------------------------+"
LOCATE 5, 7: INPUT ; "n"; Ni$
IF INSTR(Ni$, "'") THEN GOTO begin
IF VAL(Ni$) = 0 THEN GOTO eind
INPUT ; " d"; di$
IF VAL(di$) < 1 THEN GOTO begin

LOCATE lin, 1
Readst n, Ni$: Readst d, di$
Dup d, qx: Rsft qx, 1
Printn n, "  n = ", "", 2
Printn d, "  d = ", "", 2

Letf p0, 0: Letf p1, 1
Letf q0, 1: Letf q1, 0: t = 0
DO
   t = t + 1 '                       Euclid's algorithm:
   Divd n, d, a '                    partial quotient a_t
   Mult p1, a, t0: Add p0, t0 '      p_t = p_t-2 + a_t * p_t-1
   Mult q1, a, t0: Add q0, t0 '      q_t = q_t-2 + a_t * q_t-1
   Swp n, d: Swp p0, p1: Swp q0, q1
   '
   Printn a, "", "    (" + LTRIM$(STR$(t)) + ")", 1
   Printn p1, "  ", "", 1
   Printn q1, "  ", "", 1
   '
   Squ q1, t0
   r = Cmp(t0, qx) = 1 '             check convergence
LOOP UNTIL Isf(d, 0) OR r

e = INT(Bitl(q1) * .60206)
Printr p1, q1, "p/q = ", e
Prints "", 1
lin = CSRLIN: GOTO begin

eind:
LOCATE lin, 1
g$ = STR$(CSNG(TIMER - tim#))
Prints "Timer:" + g$ + " s", 1
CALL Term
SYSTEM

