How can I generate the Rowland prime sequence idiomatically in J?
Posted
by Gregory Higley
on Stack Overflow
See other posts from Stack Overflow
or by Gregory Higley
Published on 2010-06-10T08:53:19Z
Indexed on
2010/06/10
10:02 UTC
Read the original article
Hit count: 310
If you're not familiar with the Rowland prime sequence, you can find out about it here. I've created an ugly, procedural monadic verb in J to generate the first n terms in this sequence, as follows:
rowland =: monad define result =. 0 $ 0 t =. 1 $ 7 while. (# result) < y do. a =. {: t n =. 1 + # t t =. t , a + n +. a d =. | -/ _2 {. t if. d > 1 do. result =. ~. result , d end. end. result )
This works perfectly, and it indeed generates the first n terms in the sequence. (By n terms, I mean the first n distinct primes.)
Here is the output of rowland 20
:
5 3 11 23 47 101 7 13 233 467 941 1889 3779 7559 15131 53 30323 60647 121403 242807
My question is, how can I write this in more idiomatic J? I don't have a clue, although I did write the following function to find the differences between each successive number in a list of numbers, which is one of the required steps. Here it is, although it too could probably be refactored by a more experienced J programmer than I:
diffs =: monad : '}: (|@({.-2&{.) , $:@}.) ^: (1 < #) y'
© Stack Overflow or respective owner