In today’s Programming Praxis exercise, our goal is to calculate the Mersenne prime exponents up to 256. Let’s get started, shall we?

A quick import:

import Data.Numbers.Primes

The Mersenne primes can be determine with a simple list comprehension. Although the Lucas-Lehmer test officially doesn’t work for M_{2}, in practice it works just fine so there is no need to make it a special case.

mersennes :: [Int]
mersennes = [p | p <- primes,
iterate (\n -> mod (n^2 - 2) (2^p - 1)) 4 !! p-2 == 0]

A test shows that the algorithm is working correctly. Piece of cake.

main :: IO ()
main = print $ takeWhile (<= 256) mersennes
== [2,3,5,7,13,17,19,31,61,89,107,127]

### Like this:

Like Loading...

*Related*

Tags: bonsai, code, Haskell, kata, mersenne, praxis, primes, programming

This entry was posted on June 3, 2011 at 12:01 pm and is filed under Programming Praxis. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

## Leave a Reply