# Print square numbers from 1 to 9999 (non-tradfn)

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

• Note that (n + 1)² = n² + (2n+1). That's a recurrence relation between a square and the next square. If you're going to compute all squares between 1² and 99², you don't need to perform any multiplication at all: just add the next odd number to the current square, and you'll get the next square.
– Stef
Commented Dec 27, 2021 at 10:26
• @Stef yeah I know Commented Dec 27, 2021 at 14:38

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.

• @Fmbalbuena As another user here once said to me, if I wrote a new program from scratch every time I was asked to do a code review, there wouldn’t be much reason to employ those other programmers, would there? Commented Dec 26, 2021 at 18:40
• @Fmbalbuena Anyway, this sounds like a learning exercise that you want to complete yourself. Commented Dec 26, 2021 at 18:41
• @Fmbalbuena You need to stop demanding code from people. Commented Dec 26, 2021 at 18:44
• @Fmbalbuena Okay, I might’ve been a little too flippant before. The site is a place for people to come get advice on how to improve their code. Rewriting the code can be a good way to demonstrate a piece of advice, but it often isn’t. In this case, I suggested a completely different algorithm. There wouldn’t really be any point in writing that program here; it would have nothing in common with yours. You’d be better off doing it yourself as an exercise. Commented Dec 26, 2021 at 21:04