Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- This is pseudocode for a space-optimized recursive implementation of the Karatsuba multiplication algorithm.
- MUL(X,Y,N):
- ;X points to the first multiplicand of N digits
- ;Y points to the second multiplicand of N digits
- ;N is an integer power of 2
- ;Assumes yucky big endian
- X.loc = scrap-6+4N ;\
- Y.loc = X.loc+N ; |The location of the local X,Y, and Z vars
- Z.loc = Y.loc+N ; |M is the location of the results of sub multiplies
- M.loc = X.loc-N ;/
- IF N==1: ;\
- X*Y->Z[0:2] ; |Base Case
- RETURN ;/
- COPY(X,inputX,N) ;Copy the input X to the local X variable
- COPY(Y,inputY,N) ;Copy the input Y to the local Y variable
- MUL(X[N/2:N],Y[N/2:N],N/2) ;Multiply the bottom half of the digits of X and Y
- COPY(Z[N:2N],M,N) ;Copy the result of the previous multiply to the bottom half of Z
- MUL(X[0:N/2],Y[0:N/2],N/2) ;Multiply the top half of the digits of X and Y
- COPY(Z[0:N],M,N) ;Copy the result of the previous multiply to the top half of Z
- sign=0
- SUB(X[0:N/2],X[N/2:N],N/2) ;Subtract the bottom half of X from the top half, returning flags
- IF underflow
- NEG(X[0:N/2],N/2)
- sign=1
- SUB(Y[0:N/2],Y[N/2:N],N/2) ;Subtract the bottom half of Y from the top half, returning flags
- IF underflow
- NEG(Y[0:N/2],N/2)
- sign=~sign
- MUL(X[0:N/2],Y[0:N/2],N/2)
- SUB(M[0:N],Z[0:N],N)
- SUB(M[0:N],Z[N:2N],N)
- IF sign==1
- ADDir(Z[0:3N/2],M[0:N],N) ;ADD N digits, then continue as long as there is overflow
- RETURN
- ELSE
- SUBir(Z[0:3N/2],M[0:N]) ;SUB N digits, then continue as long as there is underflow
- RETURN
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement