SketchyLISP Reference |
Copyright (C) 2006 Nils M Holm |
<<[reverse] | [Index] | [string]>> |
Conformance: R5RS (Restrictions: Result is an integer. )
Purpose: Compute the square root of a natural number. (In fact, this function computes the greatest integer that is no greater than the square root of the given argument.)
Arguments:
X - square of root to extract
Model:
(define (sqrt square) (letrec ((sqr (lambda (x last) (cond ((and (n<= (n* x x) square) (n> (n* (n+ x 1) (n+ x 1)) square)) x) (#t (sqr (nquotient (n+ x (nquotient square x)) 2) x)))))) (sqr square 0)))
Implementation:
(define (sqrt square) (letrec ((sqr (lambda (x last) (cond ((= last x) x) ((= last (n+ x 1)) (cond ((n> (n* x x) square) (- x 1)) (#t x))) (#t (sqr (nquotient (n+ x (nquotient square x)) 2) x)))))) (cond ((negative? square) (bottom (list 'sqrt square))) (#t (sqr square 0)))))
Example:
(sqrt 144) => 12
<<[reverse] | [Index] | [string]>> |