Created
May 9, 2010 12:22
-
-
Save grahamedgecombe/395123 to your computer and use it in GitHub Desktop.
Haskell code which multiplies two numbers using addition and bit operations only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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