Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm a complete a noob to APL (I come from web development and ops), but reading the Wikipedia there is a section that says:

The following expression finds all prime numbers from 1 to R. In both time and space, the calculation complexity is O(R^2).

    (~R∊R∘.×R)/R←1↓ιR
How? What? I feel stupid now. ;-)


ιR creates an array 1...R

1↓ drops the first element of whatever is to the right (1...R)

R← just assigns the thing to the right to R, so now R is a variable containing the integers 2...R

R∘.×R creates a 2d matrix of every element in R multiplied by every other element in R

R∊ takes whatever's to the left (that matrix) and sees if any value in R is in that matrix. it spits out an array that is like 1 0 0 1 0 1 1 0, where the ones correspond to elements in R that are also in the matrix

~ just reverses that list so now we have an array thats like 0 1 1 0 1 0 0 1 which corresponds to elements in R that can't be created by multiplying any two elements of R together

/ goes through and only returns values of R that correspond to those 1's

the flow is like this:

  R←5
  ιR
    1 2 3 4 5
  1↓1 2 3 4 5
    2 3 4 5
  R←2 3 4 5
  R∘.×R
     4  6  8 10 
     6  9 12 15 
     8 12 16 20
    10 15 20 25
  R∊R∘.×R
    0 0 1 0
  ~R∊R∘.×R
    1 1 0 1
  1 1 0 1 / 2 3 4 5
    2 3 5


Thanks!


Try this one:

(2=+⌿0=X∘.|X)/X←⍳20

:-) They're equivalent, but the second should give you a bit more intuition based on your understanding of the definition of prime numbers.

Use TryAPL.org to explore the code. Evaluation is right to left with parentheses being their standard meaning. Try seeing what the left and the right sides of the / expression give you, and then try removing pieces from the left of the left side expression of / incrementally to see how its built up.

If you need help seeing what the functions do, you can see help.dyalog.com "Language Reference" That will show you what the symbols do.


You may also want to see "Game of Life in APL" on YouTube.

https://www.youtube.com/watch?v=a9xAKttWgP4


Here's an English reading of the above code:

Filter the numbers from [2,R), removing any number that is a member of the set of products of pairs of elements in [2,R).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: