I was trying to apply the Sieve of Eratosthenes to find the prime numbers within the range of 100. I understand that Mathematica has a built in procedure to find prime numbers, but I was trying to apply the sieve for myself. This code returns all numbers as prime numbers. Would someone be able to help me find the error in my code? Any advice is appreciated!

PrimesGenerator[N_] := 
 Module[{i = 1, j, k = 1, list = {}, plist = {2}},
  If[N < 1, Return[0],
   Do[AppendTo[list, k], {k, 1, N}];
   While[i < N,
    For[j = 2, j < N, j++,
     If[Mod[list[[i]], j] == 0, 
       Print[StringForm["`` is not prime!", i]]; i++, 
       AppendTo[plist, i]; i++];



  • $\begingroup$ btw, it is not good idea to use N for variable in Mathematica. $\endgroup$ – Nasser Dec 10 '19 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.