In today’s Programming Praxis exercise our goal is to implement a few functions that create integer sequences related to prime generation. Let’s get started, shall we?

As in the Scheme solution, the function names refer to their number in the On-Line Encyclopedia of Integers.

The first sequence can be written in a manner similar to the typical Fibonacci sequence solution.

a106108 :: [Integer]
a106108 = 7 : zipWith (\n r -> r + gcd n r) [2..] a106108

The next two just build on the previous one and are fairly trivial.

a132199 :: [Integer]
a132199 = zipWith (-) (tail a106108) a106108
a137613 :: [Integer]
a137613 = filter (/= 1) a132199

The shortcut function is slightly longer. We store the sum of all the previous numbers so that the function runs in O(n^{2}) rather than O(n^{3}).

shortcut :: [Integer]
shortcut = f 0 1 where
f s n = r : f (s + r) (n + 1) where r = lpd (6 - n + s)
lpd n = head $ filter (\d -> mod n d == 0) [3,5..]

Some tests to see if we’re getting the correct output:

main :: IO ()
main = do print $ take 65 a106108
print $ take 104 a132199
print $ take 72 a137613
print $ take 72 shortcut

Yup. Piece of cake.

### Like this:

Like Loading...

*Related*

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

This entry was posted on November 12, 2010 at 10:38 am 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