I am attempting to implement the Sieve of Sundaram:

Start with the list of integers 1,2,...,n. For every pair of integers (i,j) satisfying 1<=i<=j and i+j+2ij<=n, remove the number i+j+2ij from the list. Take all the numbers still in the list: double them and add 1 to each. This results in a list of all the odd primes below 2n+2.

Here's the code I wrote:

sundaram[n_Integer] := [
  Do[i = 1, n, 1,
   Do[j = 1, n, 1,
    If[i + j + 2*j*i <= n, AppendTo[list1, i + j + 2*j*i], Break[]];
    If[MemberQ[list1, i], Break[], AppendTo[list2, 2*i + 1]]

Since I am trying to teach myself Mathematica, I'm not sure what has gone wrong, these are some errors that are showing up: enter image description here

I am unable to make sense of these errors. I'd like to know how I can fix the syntaxes in my module.

  • 1
    $\begingroup$ 1) This is not the correct syntax for Do. You should read the documentation of Do for examples. 2) You need to define list1 as something before running this, otherwise you are appending to something undefined. $\endgroup$ Mar 22 '21 at 7:54

Usually I try to avoid global variables that don't hold long living data. Especially in this function, which should in this implementation begin with Block[{list1={},list2={}},etcetc] instead of just [etcetc]... scoping. Your Do[i=1,n,1,stuff] should be more like Do[stuff,{i,1,n,1}] or just Do[stuff,{i,n}].

There's a million ways to do this in Mathematica, all valid depending on use case. After getting your implementation to work, here's a mildly interesting one to look at

2Delete[Range@n,Flatten[Table[{i+j+2i j},{j,(Sqrt[1+2n]-1)/2},{i,(n-j)/(1+2j)}],1]]+1

Btw this is an interesting sieve I didn't know about! Edit: I suppose I'm mostly just expanding on Marius Ladegård Meyer's comment, now that I read this.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.