3 ms·
I don't know what a Pythagorean triplet is but for primes you can do it as follows in J. 1. The primitive p: generates the nth prime number so, p:0 generates t
by max_ 3y ago
I don't know what a Pythagorean triplet is but for primes you can do it as follows in J.
1. The primitive p: generates the nth prime number so, p:0 generates the first prime number 2, p:1 generates the 2nd prime number.
P: 6 generates the 6th prime number 17.
2. P: supports arrays so p: 0 1 2 3 will print the prime numbers at index 0, 1, 2 & 3. Which are 2 3 5 7.
3. The primitive/verb i. Generates a sequential list. So i. 5 will generate 0 1 2 3 4
4. p: can consume other verbs like i:*
So to print the first 1,000 prime numbers, it is simply p: (i.1000)
- OskarS 3y agoThis is not quite the problem I was asking (i wanted to know how many numbers smaller than N this is true for, not the first N numbers it's true for), but it illustrates my point anyway: the i.1000 generates an array of all numbers [0,1000) that is then immediately discarded. In imperative and functional languages, you don't need to do that: in an imperative language it's just loop counter, and in a functional language with lazy evaluation (e.g. Haskell), it's a lazy list that doesn't ever store all 1000 numbers. My question is: will J cleverly optimize away the i.1000 array? Is it lazily generated, like in Haskell? Or is this just one of those "we don't really care about the memory of the i.1000 array, it's usually small in practice"? Like, for high performance stuff, it seems relevant to me that you spend an extra O(n) memory for no real reason.
- max_ 3y agoSo basically you already have an arbitrary list of 1000 numbers. That may or may not be prime? And you want to know how many are prime? (Let me know if I am wrong) 1. Pick the highest number, H in the arbitrary list of 1000 numbers. 2. Generate all prime numbers up to the highest number, H. 3. Use e., Verb also known as member of to check for prime numbers present in arbitrary list. +/(all prime numbers up to H e. arbitrary list of 1000 numbers) will give you the number of items in the arbitrary list that are prime. > will J cleverly optimize away the i.1000 array? The primitives & verbs in array languages are designed to be as fast and efficient as possible. So even if your code is mediocre, it will perform better that any mediocre imperative code.
- dzaima 3y agoI believe J doesn't have any optimizations specifically for the problem of large temporary arrays (not to say that such can't exist, but I don't think anyone's written such yet). With multiple temporary operations, each making a temporary array larger than cache, it could in fact end up slower than mediocre imperative scalar code.
- max_ 3y agoThanks for the insight.