Previous Page

The Sieve of Atkins - Java GUI

Copy and Paste the following code into your favorite Java Integrated Development Environment (IDE) - compile and run.

Here is the image file if you want.(NOTE: Not needed for the program to work.)
Place it in the same directory as your .java file atkins_sieve.png


/***********************************************************************************
/ Name: Brian Butler
/ Class: 9:00am - 10:45 
/ Professor: Gary Hartell
/ Date Finished: May 2, 2011
/
/ Assignment:Sieve of Atkin
/
/					   					 Descripion:
/		This program uses the Sieve of Atkin to find all of the prime numbers up to
/		 and including the integer entered by the user.
/
/
************************************************************************************/

/***********************************************************************************
/							Algorithm:(taken from Wikipedia.com)
/
/		1. Create a result list filled with 2, 3, and 5.
/		2. Create a sieve list with an entry for each positive integer;
/			all entries of this list should initially be marked nonprime.
/		3. For each entry number n in the sieve list, whith modulo-sixty remainder r:
/				a. If r is 1,13, 17, 29, 37, 41, 49, or 53, flip the entry for each 
/					possible solution to 4x^2 + y^2 = n
/				b. If r is 7, 19, 31, or 43, flip the entry for each possible solution 
/					to 3x^2 + y^2 = n
/				c. If r is 11, 23, 47, or 59, flip the entry for each possible solution 
/					to 3x^2 - y^2 = n when x > y
/				d. If r is something else, ignore it completely
/		4. Start with the lowest number in the sieve list.
/		5. Take the next number in the sieve list still marked prime.
/		6. Include the number in the results list.
/		7. Square the number and mark all multiples of that square as nonprime.
/		8. Repeat steps five through eight.    
/
************************************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import static java.lang.Math.*;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
public class atkinsJFrame extends JFrame
{
	
	private JLabel  inputL;
					  
	private JTextField inputTF;
	
	private static JTextArea outputTA;
	
	private JScrollPane scrollText;//creates the scroll feature for JTextArea
														 
	private JButton calculateB, exitB, clearB;

	private CalculateButtonHandler cbHandler;
	private ExitButtonHandler ebHandler;
	private ClearButtonHandler clbHandler;	
	
	private static int WIDTH = 1024;
     private static int HEIGHT = 750;	
		
   public atkinsJFrame()
	{
     Font font = new Font("Courier New", Font.BOLD, 20);
	Font font2 = new Font("Verdana Bold", Font.PLAIN, 32);
	Font font3 = new Font("Times New Roman", Font.BOLD, 20);
		
	JLabel inputL = new JLabel("Please enter an integer to find"+
						  " all the prime numbers up to that number:");
	inputL.setFont(font3);
						  
	inputTF = new JTextField(3);
	inputTF.setFont(font2);
	
	outputTA = new JTextArea("",10,10);
	outputTA.setFont(font);
	outputTA.setBorder(BorderFactory.createEmptyBorder(50, 50, 20, 40));
	outputTA.setLineWrap(true);
     outputTA.setWrapStyleWord(true);
	  
       // the code below is for adding an image to the background of the window
	 
	  	final ImageIcon imageIcon = new ImageIcon("atkins_sieve.png");
	outputTA = new JTextArea("",10,10) {
      Image image = imageIcon.getImage();

      Image grayImage = GrayFilter.createDisabledImage(image);
      {
        setOpaque(false);
      }

      public void paint(Graphics g) {
        g.drawImage(grayImage, 0, 0, this);
        super.paint(g);
      }
    };
	outputTA.setFont(font);
	outputTA.setBorder(BorderFactory.createEmptyBorder(50, 50, 20, 40));
	outputTA.setLineWrap(true);
   outputTA.setWrapStyleWord(true);
		
    
     scrollText = new JScrollPane(outputTA);//adds the scroll feature to the outputTA
     scrollText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);		
	 calculateB = new JButton("Calculate");
      cbHandler = new CalculateButtonHandler();
      calculateB.addActionListener(cbHandler);
	 calculateB.setFont(font2);
	 
	 exitB = new JButton("EXIT");
      ebHandler = new ExitButtonHandler();
      exitB.addActionListener(ebHandler);
	 exitB.setFont(font2);
	 
	 clearB = new JButton("Clear All");
      clbHandler = new ClearButtonHandler();
      clearB.addActionListener(clbHandler);
	 clearB.setFont(font2);	 

	 
	 setTitle("Atkin's Sieve");		
            
      Container myWindow = getContentPane();
      myWindow.setLayout(null);
		
	 
	       calculateB.setLocation(794, 5);
		  exitB.setLocation(525, 665);
		  clearB.setLocation(250, 665);
		  inputL.setLocation(6,5);
		  inputTF.setLocation(608,5);
		  scrollText.setLocation(5,50);		 
			
         
		  calculateB.setSize(210,40); 
            exitB.setSize(225, 40);
		  clearB.setSize(225, 40);
		  inputL.setSize(660,40);
		  inputTF.setSize(185,40);
		  scrollText.setSize(1000,610);
		  
		  myWindow.add(calculateB);          
            myWindow.add(exitB);
		  myWindow.add(clearB);
		  myWindow.add(inputL);
		  myWindow.add(inputTF);
		  myWindow.add(scrollText);
		 
		  
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);  
	     
          

 	  }
	  
	   private class CalculateButtonHandler implements ActionListener
      {//start Calculate button handler class
      	 public  void actionPerformed(ActionEvent e)
      	 {//start actionPerformed
				   outputTA.setText("");
	  		 try
	   	 {//start try		
	       	   int[] primes;	 
 	       		int arraySize;		
		    
		        	 arraySize =Integer.parseInt(inputTF.getText());                  
              	    primes = AtkinSieve.findPrimes(arraySize); 
						             
       		 for (int prime : primes)
	    		 {	
       		    outputTA.append(prime + " ");	
      		 }      
		 
	       }//end try
			 
		 catch (NumberFormatException nfeRef)
		 {
				JOptionPane.showMessageDialog(null,"Please enter only integers ",
								 "INPUT ERROR!",JOptionPane.ERROR_MESSAGE);
				inputTF.setText("");
				inputTF.requestFocusInWindow();										
		 }                                
 	  	}//end actionPerformed 
	}//end Calculate button handler class
	
      public static class AtkinSieve
	   {     
      	  public static int[] findPrimes(int arraySize)
	    	  {//start public static int
         	     boolean[] isPrime = new boolean[arraySize + 1];
           		  double sqrtArraySize = sqrt(arraySize);
		  		/******************************************************************************     
													 put in candidate primes:  
													 integers which have an odd number of
													 representations by certain quadratic forms													 
				 ******************************************************************************/
            for (int x = 1; x <= sqrtArraySize; x++)
		      {
                for (int y = 1; y <= sqrtArraySize; y++) 
			       {
                    int n = 4 * x * x + y * y;
						  
                    if (n <= arraySize && (n % 12 == 1 || n % 12 == 5)) 
			           {
                        isPrime[n] = !isPrime[n];
                    }

                    n = 3 * x * x + y * y;
						  
                    if (n <= arraySize && (n % 12 == 7))
			           {
                        isPrime[n] = !isPrime[n];
                    }

                    n = 3 * x * x - y * y;
						  
                    if (x > y && (n <= arraySize) && (n % 12 == 11))
			           {
                        isPrime[n] = !isPrime[n];
                    }
                }
            }
				/***************************     Eliminate composites by sieving    ************/
            for (int n = 5; n <= sqrtArraySize; n++) 
		      {
                if (isPrime[n])
			       {
                    int omit = n * n;
						  
                    for (int k = omit; k <= arraySize; k +=omit) 
			           {
                        isPrime[k] = false;
                    }
                }
            }
				
            int[] primes = new int[arraySize];
            int found = 0;
				
            if (arraySize > 2)
		      {
                primes[found++] = 2;
            }
            if (arraySize > 3) 
		      {
                primes[found++] = 3;
            }
            for (int n = 5; n <= arraySize; n ++)
		      {
                if (isPrime[n]) 
			       {
                    primes[found++] = n;
                }
            }
            return Arrays.copyOf(primes, found);
       }//end public static int
    }//end static class AtkinSieve

   
		
   	 private class ExitButtonHandler implements ActionListener
       {
      	 public void actionPerformed(ActionEvent e)
          {
        		  System.exit(0);//allows the exit button to close the JFrame window      
      	 }
       }// End of EXIT BUTTON actionPerformed 
	 
	 	 private class ClearButtonHandler implements ActionListener
       {
          public void actionPerformed(ActionEvent e)
          {
                 inputTF.setText("");
		           outputTA.setText("");
		      	  inputTF.requestFocusInWindow();
          }
       }


   public static void main(String[] args)
   {	 
       atkinsJFrame sieveObject = new atkinsJFrame();
		 
         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
         sieveObject.setBounds((int) screenSize.getWidth() - WIDTH, 0, WIDTH, HEIGHT);
			sieveObject.setLocationRelativeTo(null);
			
   }	
}

//END OF CODE