prologues:=2;

vardef pgcd(expr A,B) = 
    save a,b,r;
    numeric a,b,r;
    a := A; b := B;
    forever: 
        r := a mod b;
        a := b; b := r;
        exitunless r > 0;
    endfor;
    a
enddef;

vardef prem(expr P)=
  boolean reponse;
  reponse=false;
  numeric div;
  div=0;
  if P=1:
    div:=1;
  else:
    for g=2 upto P-1:
      if (pgcd(P,g)<>1):
	div:=div+1;
      fi;
    endfor;
  fi;
  if div=0:
    reponse:=true;
  fi;
  reponse
enddef;

vardef ulam(expr nb,pas)=
  save $;
  picture $;
  $=image(
    if prem(nb)=true:
      fill fullcircle scaled 8mm withcolor 0.9white;
      label(TEX(""&decimal(nb)&""),(0,0));
    else:
      label(btex $\star$ etex,(0,0));
    fi;
    pair ptd;
    ptd=(0,0);
    u:=8mm;
    k:=nb;
    for l=1 upto pas:
      if (l mod 2)=1:
	for j=1 upto l:
	  k:=k+1;
	  if prem(k)=true:
	    fill fullcircle scaled 8mm shifted (ptd+u*(0,j)) withcolor 0.9white;
	    label(TEX(""&decimal(k)&""),ptd+u*(0,j));
	  else:
	    label(btex $\star$ etex,ptd+u*(0,j));
	  fi;
	endfor;
	ptd:=ptd+u*(0,l);
	for j=1 upto l:
	  k:=k+1;
	  if prem(k)=true:
	    label(TEX(""&decimal(k)&""),ptd+u*(j,0));
	  else:
	    label(btex $\star$ etex,ptd+u*(j,0));
	  fi;
	endfor;
	ptd:=ptd+u*(l,0);
      fi;
      if (l mod 2)=0:
	for j=1 upto l:
	  k:=k+1;
	  if prem(k)=true:
	    label(TEX(""&decimal(k)&""),ptd+u*(0,-j));
	  else:
	    label(btex $\star$ etex,ptd+u*(0,-j));
	  fi;
	endfor;
	ptd:=ptd+u*(0,-l);
	for j=1 upto l:
	  k:=k+1;
	  if prem(k)=true:
	    label(TEX(""&decimal(k)&""),ptd+u*(-j,0));
	  else:
	    label(btex $\star$ etex,ptd+u*(-j,0));
	  fi;
	endfor;
	ptd:=ptd+u*(-l,0);
      fi;
    endfor;
    );
  $
enddef;

input TEX;


beginfig(1);
  draw ulam(1,10);
endfig;


beginfig(2);
  draw ulam(41,15);
endfig;
end