Previous Page

The Sieve of Sundaram- 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 sundarams_sieve.png


/***********************************************************************************
/ Name: Brian Butler
/ Professor: Gary Hartell
/ Date: April 10, 2011
/ Assignment:Sieve of Sundaram 
/								   
/					   					 Descripion:
/		This program uses the Sieve of Sundaram to find all of the prime numbers
/       up to and including the integer	entered by the user.       
/
************************************************************************************/

/***********************************************************************************
				Algorithm:(taken from Wikipedia.com)

  Start with a list of the integers from 1 to n. From this list, remove all
  numbers of the form i + j + 2ij where:

   1)   i,j Elements of N, 1<= i<=j
   2)   i + j + 2ij <= n

 The remaining numbers are doubled and incremented by one, giving a list of the
 odd prime numbers (i.e., all primes except the only even prime 2) below 2n + 2.

 The sieve of Sundaram is equivalent to the sieve of Eratosthenes, except that
 the initial list corresponds only to the odd integers; the work of "crossing out"
 the multiples of 2 is done by the final double-and-increment step.
 Whenever Eratosthenes' method would cross out k different multiples of a prime 2i+1,
 Sundaram's method crosses out i + j(2i+1) for i <= j <= ( arraySize / 2).
************************************************************************************/


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import java.awt.Color;


public class sundaramsJFrame 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 sundaramsJFrame()
	{
     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);
	
	 // the code below is for adding an image to the background of the window
     
	final ImageIcon imageIcon = new ImageIcon("sundarams_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("Sundaram'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);
		 
		  
	   setSize(WIDTH, HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);       

 	  }
	  
	   private class CalculateButtonHandler implements ActionListener
       {
       public  void actionPerformed(ActionEvent e)
       	{
		 outputTA.setText("");
		try
		{		
	        int[] primes;      
	 
 	   int arraySize;		
		    
			arraySize =Integer.parseInt(inputTF.getText());                  
                  primes = SundaramSieve.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();
										
			}                                
 	    	} 
	}
 public static class SundaramSieve 
 {         
        	public static int[] findPrimes(int arraySize)
	     {//start public static int
            int n = arraySize / 2;
				
            boolean[] isPrime = new boolean[arraySize];
				
            Arrays.fill(isPrime, true);
				
            for (int i = 1; i < n; i++)
		      {
                for (int j = i; j <= (n - i) / (2 * i + 1); j++)
			       {
                    isPrime[i + j + 2 * i * j] = false;
                }
            }
								
            int[] primes = new int[arraySize];
            int found = 0;
		  
            if (arraySize > 2)
		 	   {
                primes[found++] = 2;
            }
            for (int i = 1; i < n; i++)
		      {
                if (isPrime[i])
		          {
                    primes[found++] = i * 2 + 1;
                }
             }				
            return Arrays.copyOf(primes, found);
        }//end of public static int
 }

   
		
   	 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)
   {	 
       sundaramsJFrame sieveObject = new sundaramsJFrame();
		 
       sieveObject.setLocationRelativeTo(null);
   }	
}
//END OF CODE