I’m trying to port a .M file (Objective C?) to Xojo.
The function prints prime numbers in a spiral fashion, that is if a number is prime it gets painted else it is omitted. The code is only a few lines but I’m struggling.

m = 1001; % size of A
m2 = m*m;
length = 1;
direction = 1; % 1:R, 2:U, 3:L, 4:D
A = zeros(m, m);
x = ceil(m/2);
y = x;
ind = 1;
A(y, x) = ind;
while (ind < m2)
for i = 1:2
for j = 1:length
ind = ind + 1;
if (ind > m2), break; end
switch direction
case 1
x = x + 1;
case 2
y = y - 1;
case 3
x = x - 1;
case 4
y = y + 1;
end
A(y, x) = ind;
end
if (ind > m2), break; end
direction = mod(direction, 4) + 1;
end
length = length + 1;
end
B = isprime(A);
imagesc(B);
axis equal;
axis off;[/code]

My Xojo code sofar:

[code] dim X as Integer
dim n as Integer = 1000
dim Y as Integer
dim i as integer
dim direction as integer = 1
dim ind integer = 1

x = Round(Canvas1.Width/2)
y = Round(Canvas1.Height/2)

for i = 1 to n

ind = ind+1
direction = (direction mod 4 )+ 1
select case direction
case 1
x = x + 1
case 2
y = y - 1
case 3
x = x - 1
case 4
y = y + 1
end select
if IsPrime(i) then
g.Pixel(x,y) = rgb(0,0,0)
end if

next[/code]

IsPrime is a separate standard function and returns true when a number is Prime
The problem I have is the Ind value. It controls the direction of the drawing. I don’t get that running.

The spiral fashion is like

It is called the Ulam spiral when you only show the primes as dots

If counter = 0 Then
counter = Sqrt(stepper - start - 1)
direction = (direction + 1) Mod 4
Else
counter = counter - 1
End
g.DrawString(Str(stepper), 10, (stepper - start + 2) * 20)
g.DrawString(Str(counter), 80, (stepper - start + 2) * 20)
g.DrawString(Str(direction), 150, (stepper - start + 2) * 20)
Select Case direction
Case 0
x = x + distance
Case 1
y = y - distance
Case 2
x = x - distance
Case 3
y = y + distance
End
If x > 220 Then
g.DrawString(Str(stepper), x, y)
End

Very good! Only the self.maximize throws a stack overflow. Never mind.

I modified the code so I can paint pixels instead of numbers:

[code] Dim start As Integer = 1
Dim maximum As Integer = 10000

’ Self.Maximize()

Dim x As Integer = Me.Width \ 2
Dim y As Integer = Me.Height \ 2
Dim distance As Integer = 1
Dim counter As Integer = 1
Dim direction As Integer = 0

For stepper As Integer = start To maximum

If counter = 0 Then
counter = Sqrt(stepper - start - 1)
direction = (direction + 1) Mod 4
Else
counter = counter - 1
End
Select Case direction
Case 0
x = x + distance
Case 1
y = y - distance
Case 2
x = x - distance
Case 3
y = y + distance
End
If IsPrime(Stepper) then
g.Pixel(x,y) = rgb(0,0,0)
end if

Next[/code]

The thing is, when I enlarge the maximum integer, It becomes slow because of the IsPrime function. I will try to optimize that.

Thanks very much, you have really put me on track!

Yes!
It draws and calculates the primes up to 200,000 in about 2 secs.
[Edit] some optimization… first create a Picture object and draw into that cuts time in half…