I'm making a simple program that outputs the squares. I have a question: Is there a way to improve the speed but make the Code readable?
Code
∇F
f ← 1
:While f ≢ 100
⎕ ← f × f
f ← f + 1
:EndWhile
∇
F
Output: a lot of squares
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.
Sign up to join this communityI'm making a simple program that outputs the squares. I have a question: Is there a way to improve the speed but make the Code readable?
Code
∇F
f ← 1
:While f ≢ 100
⎕ ← f × f
f ← f + 1
:EndWhile
∇
F
Output: a lot of squares
When optimising APL programs, always strive for few computations on large arrays.
Here, you want to compute the first 99 squares, so start by generating the 99 first integers: ⍳99
Now square them, either with (⍳99)*2
or 2*⍨⍳99
or by multiplying them with themselves: ×⍨99
Ideally, you'd want to print them as a single printing action (⎕←
) too, so format the list into a character array, which puts single spaces between the numbers: ⍕×⍨⍳99
Then substitute linebreaks at all positions that are equal to spaces: (⎕UCS 10)@{' '=⍵}⍕×⍨⍳99
This gives us our complete solution: ⎕←(⎕UCS 10)@{' '=⍵}⍕×⍨⍳99
Try it online!
Oh, an APL question.
I believe you’d be better off generating a vector of the numbers between the ceiling of the square root of your lower bound and the floor of the square root of the upper bound, then multiplying that with itself, using +.×
. This computation will be much faster than the loop, because it will vectorize.