I don’t intend for this blog to become a dumping ground for code snippets, but sometimes the temptation is too strong. Here’s a simple but fast function for computing a factorial, using the binary splitting algorithm from this page.

```
factorial :: Integral a => a -> a
factorial n = split n 0
where split a b = let d = a - b
in if d < 0
then 0
else case d of
0 -> 1
1 -> a
2 -> a * (a - 1)
3 -> a * (a - 1) * (a - 2)
_ -> let m = (a + b) `div` 2
in split a m * split m b
```

Nice code. Looking at the reference though, isn’t the performance improvement dependent upon using FFT or such like for the multiplication operation?

~Matt

Yes, a fast multiply is required, but that’s common nowadays.

I’m looking forward to your Haskell book so I’m cringing at that case statement! Wouldn’t pattern matching be more Haskellish?

The case statement is pattern matching. It just happens that it’s doing so on integer patterns. Trying to hoist the pattern match up to the function definition level would make the code longer, weirder, or both. Try it and see.

Just wondering why the base case for 2 and 3 has been included. Can’t those be captured by the 0 and 1 cases?