#lang racket ;; ------------------------------------------------------------------------ ;; The only multiplication operators we have for the this exercise: ;; ------------------------------------------------------------------------ (define (half n) (quotient n 2)) ; or (arithmetic-shift n -1)) (define (double 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 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 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 item) (~a item #:min-width 6 #:align 'right #:left-pad-string " ")) ;; --------------------------------------------------------------------------