- /
-
sieve of Eratosthenes to 82944
on 30 Nov 2023
- 8
- 40
- 0
- 0
- 270
drawframe(24);
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=6;
max=(sf*f)^2; % in this instances max = [36,144,324,576,900,1296,1754,...,79524,82944]
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
![](/responsive_image/300/300/0/0/0/cache/matlabcentral/communitycontests/uploaded_files/19529/animation.gif?a=true)