It can be improved by adding a space, the correct indentation, and the correct function body:
int peasant_mult (int a, int b) { for (p = 0; p += (a & 1) * b, a != 1; a /= 2, b *= 2); return p;}
Cm? Now it turns out how the three parts of the for declaration are used. Remember that programs are written primarily for the human eye. Unreadable code is always bad code.
And now, for my personal entertainment, the tail recursive version:
(defun peasant-mult (ab & optional (sum 0))
"returns the product of a and b,
achieved by peasant multiplication. "
(if (= a 1)
(+ b sum)
(peasant-mult (floor (/ a 2))
(* b 2)
(+ sum (* b (logand a 1))))))
Svante Nov 04 '08 at 4:36 2008-11-04 04:36
source share