Sieve of eratosthenes processing problem not drawing rectables in Processing

54 Views Asked by At

I am trying to create the Sieve of Eratosthenes problem where I print out a grid from 2 to 100 and then cover all non-prime numbers with a rectangle. I can only get it to check one divisor between 2 and 10. I cant get it to loop through all divisors. my current version doesn't print any rectangles what so ever but it feels like it should be because reading it it looks like if variable a is less than 10 check if the number in that location is divisible by a. if it is print a rectangle there. once it checks all of those it add 1 to a. Where am I going wrong here?

int a=2;

void setup()
{
  size(600, 600);

  rectMode(CORNER);
  textSize(17);
  background(0);
  for (int x = 0; x < 10; x++)
  {
    for (int y =0; y<11; y++)
    {
      if ((x)+((y-1)*10)+1>1)
      {
        fill(255);

        text((x)+((y-1)*10)+1, x*50+30, y*50);
      }
    }
  }
}

void draw()
{
  for (int x = 0; x < 10; x++)
  {
    for (int y =0; y<10; y++)
    {
      while (a<10)
      {
       
        if ((x)+((y-1)*10)+1%a==0)
        {
          fill(50, 50, 200);
          rect((x)*50+30, (y)*50+30, 30, 30);
        }
         a++;
      }
    }
  }
}
1

There are 1 best solutions below

0
Mruk On BEST ANSWER

You have several problems in Your solution.

  • ((x)+((y-1)*10)+1>1) formula is overcomplex for this problem,
  • void draw() is a loop, so Your 'a' variable will never go back to value 2.
  • Use System.out.println(); wherever You are not sure what is going on.

So, here is the cleaner concept of Your problem:

  • in Your case there is no need to call draw(),
  • set 'a' value every time before while(), not just once before setup(),
  • draw Your boxes just inside the same place as text()
    void setup() {
        size(600, 600);
        background(0);
        fill(255);
        for (int y=0; y<10; y++) {
            for (int x=1; x<=10; x++) {
                System.out.println(x + ", " + y + ": " + (x+y*10));
                int a=2;
                textSize(26);
                while (a<=Math.sqrt(x+y*10)) {
                    if ((x+y*10)%a == 0) {
                        System.out.println(a+": "+x+", " +y+": "+(x+y*10)); 
                        textSize(12);  
                    }
                a++;
                }
                text(x+y*10, x*50, y*50+50);
            }
        }
    }   
    void draw() {
    }