## Rowland’s Prime-Generating Function

### November 12, 2010

Regular readers of Programming Praxis know of my affinity for prime numbers. Today’s exercise is based on a prime-generating sequence described by Eric Rowland. Consider the sequence *a*_{1} = 7, *a _{n}* =

*a*

_{n-1}+ gcd(

*n*,

*a*

_{n-1}): 7, 8, 9, 10, 15, 18, 19, 20, 21, 22, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 69, 72, 73. Taking the differences between successive elements of the sequence gives a second sequence 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1. All the elements of that sequence are either 1 or prime. Eliminating the 1s gives a third sequence of primes that begins 5, 3, 11, 3, 23, 3, 47, 3, 5, 3, 101, 3, 7, 11, 3, 13, 233, 3, 467, 3, 5, 3, 941, 3. Rowland has proved that all elements of the sequence are either 1 or prime; it is conjectured but not proven that all the odd primes appear in the sequence.

It is possible to shortcut the sequence by omitting the 1s, since the number of 1s at any point can be pre-computed. If we have a least-prime-divisor function lpd, then Vladimir Shevelev describes the sequence as *a*_{1} = lpd(6-1) = 5, *a*_{2} = lpd(6-2+5) = 3, *a*_{3} = lpd(6-3+5+3) = 11, *a*_{4} = lpd(6-4+5+3+11) = 3, *a*_{5} = lpd(6-5+5+3+11+3) = 23, …, and *a _{n}* = lpd(6 –

*n*+ sum(

*a*

_{1}…

*a*

_{n-1}).

Your task is to write functions that generate the three sequences, including the shortcut. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

[...] today’s Programming Praxis exercise our goal is to implement a few functions that create integer sequences [...]

My Haskell solution (see http://bonsaicode.wordpress.com/2010/11/12/programming-praxis-rowland%E2%80%99s-prime-generating-function/ for a version with comments):

My try in F#

Posted on pastebin.com, since my line count stretches the limits of polite posting here.

I memoized nearly everything, trading time for space. Python has syntactic sugar called “decorators” that works nicely for this; after defining

a decorator memoize(func), one merely need write @memoize on the line above the function definition to cache the result of calling func()

for later recursion or reuse.

Rather quick, though not as elegant or speedy as the Scheme or Haskell answers. I bet the F# answer probably wins over mine as well, but I

haven’t the ability to run F# on my laptop just yet.

You have “The primes are excluded from that sequence in Sloane’s A137613″, but I believe you mean “The ones are excluded from that sequence in Sloane’s A137613″.

Fixed.

Hey all- I used this problem to teach myself Clojure. My solution (with some testing code) can be found here: https://github.com/topher200/rowland-primes/blob/master/src/rowland_primes/core.clj.

Clojure version using O’Neil sieve for lpd function.