• Remix
  • Share
  • New Entry

  • Josh

  • /
  • ancient sieve to generate primes from 1 to 2304

on 30 Nov 2023
  • 9
  • 19
  • 2
  • 1
  • 270
drawframe(10);
Write your drawframe function below
function drawframe(f)
% code demonstrates the sieve of Eratosthenes (developed in 3rd century BCE)
% which can be used to find all primes from 1 to any given number n
% scale factor (sf) is used as a hack to achieve deeper iterations of
% algorithm despite limitatation of number of frames to 48, cost of deeper
% iterations is lower resolution as algorithm skip forward at intervales through steps
sf=1;
max=(sf*f)^2;
n=[];
% building square matrix (fxf) to max element at n(f,f)=max
for i1=1:max^(1/2):max
n=[n;i1:i1+(sf*f-1)];
end
n=n'; % important to use transpose to flip matrix so when element is referenced by index--
% and it is done so via linear indice, the value and indice are equal
[row,col]=size(n);
o=zeros(row,col);
o(1)=1;
active=2;
% while loop is used to process through all numbers from 2:max
while active<max
% core loop of algorithm iterates from current element (active) through
% remaining elements, switching corresponding values in output matrix (o)
% to 1 where those indices are multiples of active
% essentially, composite indices/numbers are switched to 1 (white) wheres
% primes are left untouched as 0 (black)
for i1=active+1:max
if o(i1)==1
continue;
elseif mod(n(i1),active)==0
o(i1)=1;
end
end
active=active+1;
end
% result is o is a bw image where black pixels (0) are prime numbers
o=o'; % after sieve is complete, use transpose to return output matrix in such a way that makes more
% visual sense in a right-to-left, top-to-bottom counting manner where 1 is
% in top left and max is in bottom right
o=imresize(o,[600 600],'box');
imshow(o);
end
Animation
Remix Tree