% A. Albert
% physicsforums.com UN: trini
% physorg.com UN: cube
% This program generates a square spiral path. The first point is given the
% number 0, then all other points are successive odd numbers ( so the path
% goes 0,1,3,5,7...

clear all
clc
clf

% Initial grid point (will be considered the number 0)
pos(1,1)=0;
pos(1,2)=0;

n=2; % Initialises the path counter
k=[1,2]; % This array is used to generate the path.
         % If we move up the grid for the first move(y+1), then we can
         % generate the clockwise spiral by moving along the cycle: 
         % 1 unit up, 1 unit right, 2 units down, 2 units left.
         % We then increase k(1) and k(2) by 2 as we will now be on the next
         % layer of the spiral and repeat the cycle.
         
for turn=1:10, % Set how many turns you want to use

    z=1;
    
    % up
    while z <= k(1) 
    pos(n,1)=pos(n-1,1);
    pos(n,2)=pos(n-1,2)+1;
    z=z+1;
    n=n+1;
    end
    z=1;
    % right
    while z <= k(1) 
    pos(n,1)=pos(n-1,1)+1;
    pos(n,2)=pos(n-1,2);
    z=z+1;
    n=n+1;
    end
    z=1;
    % down
    while z <= k(2) 
    pos(n,1)=pos(n-1,1);
    pos(n,2)=pos(n-1,2)-1;
    z=z+1;
    n=n+1;
    end
    z=1;
    % left
    while z <= k(2) 
    pos(n,1)=pos(n-1,1)-1;
    pos(n,2)=pos(n-1,2);
    z=z+1;
    n=n+1;
    end
    
    k(1)=k(1)+2;
    k(2)=k(2)+2;
    turn=turn+1
end

pathnum=size(pos);

p=1;
for m=1:pathnum(1)-1;
    % Check to see which of the path values are primes
    if isprime(m*2-1)==1
        x(p)=pos(m+1,1);
        y(p)=pos(m+1,2);
        p=p+1;
    end
end

hFig = figure(1);
set(hFig, 'Position', [100 100 800 750])

rectangle('Position',[0-0.5,0-0.5,1,1],...
          'FaceColor','b')

num = 0;

for k=1:length(x)
% Check to see if there are any elements in the blank double row and double
% column 
if (x(k) == 0 && y(k) < 0 ) || (x(k) == 1 && y(k) < -1) || (x(k) > 1 && y(k) == 0  ) || (x(k) > 1 && y(k) == 1)
    num=num+1;
end

rectangle('Position',[x(k)-0.5,y(k)-0.5,1,1],...
          'FaceColor','r')
hold on

end

num


