ScratchData LogoScratchData
Back to gtoal's profile

Sneaky multiplication! (only uses 'change' block)

GTgtoal•Created March 11, 2015
Sneaky multiplication! (only uses 'change' block)
4
2
77 views
View on Scratch

Instructions

Enter two integers. It outputs the product without using the multiply block. See inside for the code... takes a few seconds for big numbers. I wrote this because I was pondering how I had once written a multiply routine on an old computer that didn't have a hardware multiply instruction, and I was wondering if there was a better solution than the obvious loop/shift/add that we had used at the time. (Was it a PDP9? I'm struggling to remember). For some reason I never thought of this solution at the time, and I wanted to try it just now and confirm to myself that it would have worked...

Description

Uses the identity (x+1).(y+1) == xy + x + y +1 After subtracting 1 from x and y, the code adds 1 to the result, adds x, adds y, then recurses to add the product of the smaller x*y. Since the recursive call comes last, it's implemented as tail recursion by turning the code into a loop instead.

Project Details

Project ID51918954
CreatedMarch 11, 2015
Last ModifiedMarch 12, 2015
SharedMarch 11, 2015
Visibilityvisible
CommentsAllowed