Skip to content

Instantly share code, notes, and snippets.

@grahamedgecombe
Created May 9, 2010 12:22
Show Gist options
  • Save grahamedgecombe/395123 to your computer and use it in GitHub Desktop.
Save grahamedgecombe/395123 to your computer and use it in GitHub Desktop.
Haskell code which multiplies two numbers using addition and bit operations only.
import Data.Bits
-- checks if x is divisble by y
divisible :: Int -> Int -> Bool
divisible x y | y == 2 = not (testBit x 0)
| otherwise = mod x y == 0
-- multiplies x and y by manipulating bits and performing addition only
mult :: Int -> Int -> Int
mult x y | x == 0 = 0
| not (divisible x 2) = mult (clearBit x 0) y + y
| otherwise = mult (shiftR x 1) (shiftL y 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment