Grade School Multiplication
November 18, 2011
We begin with the function that displays a single multiplication. We find it easiest to plan everything first, calculating the width of the output display in the variable len
and the number of lines in the body of the multiplication in the variable lines
:
(define (mult x y)
(let* ((ys (digits y))
(len (length (digits (* x y))))
(lines (length (filter positive? ys))))
(display-right x len)
(display-right y len)
(display (repeat len #\-)) (newline)
(when (< 1 lines)
(let loop ((ys (reverse ys)) (i 0) (z 1))
(when (pair? ys)
(if (zero? (car ys))
(loop (cdr ys) i (* z 10))
(begin (display-right (* x (car ys) z) (- len i))
(loop (cdr ys) (+ i (ilog10 z) 1) 1)))))
(display (repeat len #\-)) (newline))
(display-right (* x y) len)))
We used several utility functions that aren’t shown here, though all are at http://programmingpraxis.codepad.org/AMItBoYw: digits
, which returns a list of the digits in a number, is from the Standard Prelude; repeat
returns a string consisting of n repetitions of the character c; display-right
displays a number n right-justified in a string of width len, and appends a newline; and ilog10
returns the number of digits in the input number n, minus one.
Function problem-a
takes a filename and outputs the requested multiplications:
(define (problem-a filename)
(with-input-from-file filename
(lambda ()
(let loop ((x (read)) (y (read)) (i 1))
(when (and (positive? x) (positive? y))
(display "Problem ") (display i) (newline)
(mult x y)
(loop (read) (read) (+ i 1)))))))
To solve the problem, say problem-a multiply.in
.
My quickly hacked together version in Python. Would love to see more elegant versions, but right now can’t think of one.
minor correction: instead of writing my expand_string() function, I could have used something like:
sigh… correction on my correction: I should leave the string conversion in :)
”’
My python solution
”’
i1=int(raw_input(‘enter first no’))
i2=int(raw_input(‘enter second no’))
print i1,’\n’,i2
print ‘————‘
t=i2
cnt=0
x=0
while t!=0:
x=(t%10)*i1
if cnt==0 and x!=0:
print x
elif x!=0:
print x*(cnt*10)
t=t/10
cnt+=1
print ‘————‘
print i1*i2
A Clojure solution: