// Sieve.java
// Sieve class definition
// The Sieve of Eratosthenes
// Finds all prime numbers from lowest to highest entered values
// Uses array of booleans
// Saved in jre\classes\edu\lehigh\exercises directory
package edu.lehigh.exercises;
import java.awt.*;
import javax.swing.*;

public class Sieve {
	// instance variables
	private int low;
	private int high; 
	private boolean n[ ];
	private String resultsString;

	// constructor
	public Sieve( int l, int h ) {
		low = setLow( l );
		high = setHigh( h );
		n = new boolean[ h - l + 1 ];  // n.length = h - l + 1
		resultsString = "";
	}

	// set methods for instance variables
	public int setLow( int l ) {
		if ( l < 1 )
			l = 1;
		return l;
	}

	public int setHigh( int h ) {
		if ( h < 1 )
			h = 1;
		return h;
	}

	public String getResultsString( ) {
		return resultsString;
	}

	public void initialize( ) {
	// initialize all array elements to true
		for ( int i = 0; i < n.length; i++ )
			n[ i ] = true;
	}
		
	public void findPrimes( ) {
		for ( int i = 2; i < high - 1; i++ ) {				// divisor starts with 2 always, runs up to high - 1
			for ( int j = 0; j < n.length; j++ ) {			//  j is array subscript - runs 0 to n.length - 1
				if ( n[ j ] == false )
					continue;  // no sense checking

				if ( i == j + low )				//  avoids dividing each number by itself
					continue;

				else if ( ( j + low ) % i == 0 ) {		//  j + low is actual numerator, runs low to high
					n[ j ] = false;  // toggle to false
				}
			}
		}
	}
		
	public void printPrimes( ) {
		int col = 0;
		for ( int i = 0; i < n.length; i++ ) {
			// if element is still true, its subscript is prime
			if ( n[ i ] == true ) {
				
				resultsString += ( ( i + low ) + "\t" );	// prints only primes
				col++;  // keeps track of how many primes are on the row
				if ( col % 7 == 0 )
					resultsString += "\n";  // go to new line
			}
		}
	}
}