I’m looking for a J code to do the following.
Suppose I have a list of random integers (sorted),
2 3 4 5 7 21 45 49 61
I want to start with the first element and remove any multiples of the element in the list then move on to the next element cancel out its multiples, so on and so forth.
Thus the output
I’m looking at is 2 3 5 7 61. Basically a Sieve Of Eratosthenes. Would appreciate if someone could explain the code as well, since I’m learning J and find it difficult to get most codes 🙁
Regards,
babsdoc
It’s not exactly what you ask but here is a more idiomatic (and much faster) version of the Sieve.
Basically, what you need is to check which number is a multiple of which. You can get this from the table of modulos:
|/~Every pair of multiples gives a
0on the table. Now, we are not interested in the0s that correspond to self-modulos (2 mod 2, 3 mod 3, etc; the0s on the diagonal) so we have to remove them. One way to do this is to add1s on their place, like so:This can be also written as
(=/~ + |/~) l.From this table we get the final list of numbers: every number whose column contains a
0, is excluded.We build this list of exclusions simply by multiplying by column. If a column contains a
0, its product is0otherwise it’s a positive number:Before doing the last step, we’ll have to improve this a little. There is no reason to perform long multiplications since we are only interested in
0s andnot-0s. So, when building the table, we’ll keep only0s and1s by taking the “sign” of each number (this is thesignum:*):so,
From the list of exclusion, you just
copy:#the numbers to your final list:or,