From J Wiki
Jump to navigation Jump to search

J has a primitive for working with primes p:, which trivializes this problem.

   _1 p: 20e5   NB. primes below 2 million
   p: i. 10   NB. first ten primes
2 3 5 7 11 13 17 19 23 29
   +/ p: i. _1 p: 20e5   NB. the answer

Although my initial answer is simple, I always take the time to look through the forums after finding an answer to see if any other J enthusiasts came up with something else. In this case, it was found that &. could be used remove the last p: by leveraging the fact that _1&p: and p: are inverses of each other.

NB. a look out how to invoke inverses
   _1 p:inv i. 5   NB. inv is a defined in the standard library and defined as ^:(_1)
2 3 5 7 11
   p:inv 20e5
   +/ i.&.(_1&p:) 20e5   NB. the answer using Under
   +/ _1 p:inv i. _1 p: 20e5   NB. the expanded form of what Under is doing for us

What proceeds is merely subjective.

A benefit to this, in my opinion, is that it can help simplify a tacit expression if I so chose to make one. It also allows me to utilize one of J's coolest conjunctions.

(1#._1 p:@i.@p:])   NB. uses two forks and requires an ugly space with a series of atops that uses p: twice
(1#.p:@i.@(p:inv))  NB. uses one fork and needs no spaces but still requires using p: twice
(1#.i.&.(_1&p:))    NB. one fork, no spaces, and one p:, plus it is marginally shorter, which would be good for code golfing