Programming Praxis – Two Factoring Games

In today’s Programming Praxis exercise, our goal is to implement two algorithms related to prime factors; one to calculate the home prime of a number and one to generate the Euclid-Mullin sequence. Let’s get started, shall we?

Some imports:

import Data.List
import Data.Numbers.Primes

To calculate the home prime we repeatedly concatenate the digits of the prime factors until the number is prime.

homePrime :: Integer -> Integer
homePrime = head . filter isPrime .
            iterate (read . concatMap show . primeFactors)

The Eulic-Mullin sequence can be written as a basic unfold.

euclidMullin :: [Integer]
euclidMullin = unfoldr (\p -> let a = head (primeFactors $ p + 1)
                              in  Just (a, p * a)) 1

Naturally, we need to test if we did everything correctly:

main :: IO ()
main = do print $ homePrime 99 == 71143
          print $ take 10 euclidMullin ==
                  [2,3,7,43,13,53,5,6221671,38709183810571,139]

Looks like everything is working properly.

About these ads

Tags: , , , , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: