package primegui;

/**
 * Counts the primes in [from,to). One task per range; the result is read
 * after the thread running the task has finished.
 */
public class PrimeCounter implements Runnable {

	private int from_;
	private int to_;
	private int count_;

	public PrimeCounter ( int from, int to ) {
		from_ = from;
		to_ = to;
		count_ = 0;
	}

	@Override
	public void run () {
		for ( int n = from_ ; n < to_ ; n++ ) {
			if ( isPrime(n) ) {
				count_++;
			}
		}
	}

	/**
	 * Only meaningful after the thread running this task has finished.
	 */
	public int getCount () {
		return count_;
	}

	public static boolean isPrime ( int n ) {
		if ( n < 2 ) {
			return false;
		}
		for ( int d = 2 ; (long) d * d <= n ; d++ ) {
			if ( n % d == 0 ) {
				return false;
			}
		}
		return true;
	}

}
