#lang racket ;; ------------------------------------------------------------------------ ;; The only multiplication operators we have for the this exercise: ;; ------------------------------------------------------------------------ (define half (lambda (n) (quotient n 2))) ; or (arithmetic-shift n -1))) (define double (lambda (n) (* n 2))) ; or (arithmetic-shift n 1))) ;; ------------------------------------------------------------------------ ;; Full Russian peasant multiplication, which allows m to be odd. This ;; function is an interface procedure to a local recursive helper that ;; uses an accumulator variable. ;; ------------------------------------------------------------------------ (define multiply (lambda (m n) (letrec ((loop (lambda (m n acc) (display3 m n acc) (if (zero? m) acc (loop (half m) (double n) (+ acc (if (odd? m) n 0))))))) (loop m n 0)))) ;; -------------------------------------------------------------------------- ;; This function uses a C-style format string to display its arguments. ;; Racket contains multitudes! (define display3 (lambda (m n acc) (printf "~a ~a ~a\n" (pad m) (pad n) (pad acc)))) ;; -------------------------------------------------------------------------- ;; This function creates a right-justified string of size 6 for its argument. (define pad (lambda (i) (~a i #:min-width 6 #:align 'right #:left-pad-string " "))) ;; ------------------------------------------------------------------------ ;; Performing multiplication and division with a bit-shift operation: ;; ------------------------------------------------------------------------ ;(define half (arithmetic-shift n -1)) ;(define double (arithmetic-shift n 1)) ;; --------------------------------------------------------------------------