import java.util.ArrayList;

public class Primes {
	ArrayList<Integer> primes = new ArrayList<Integer>();

	public Primes(int n) {
		initPrimes(n);
	}

	// Find the smallest prime number that is greater or equal to n
	public int nextPrime(int n) {
		while (!Main.isPrime(n)) {
			n++;
		}
		return n;
	}

	public boolean isPrime(int n) {
		// If there is no built primes list or the 0th prime (biggest prime)
		// is less than n, there is a possibility that n is a prime and we
		// need to build the ArrayList of primes to test n
		if (primes.size() == 0 || n > primes.get(primes.size()-1)) {
			buildPrimes(n);
		}

		// Returns true if n is in the primes list, false otherwise
		return primes.contains(n);
	}

	// n is the number of primes that should be in the ArrayList
	public void initPrimes(int n) {
		int prime = 2;
		for (int i = 0; i < n; i++) {
			primes.add(nextPrime(prime));
			prime = primes.get(primes.size()-1)+1;
		}
//		System.out.println(primes);
	}

	// n is the number up to which all primes should be stored
	// Example: if n is 25, then the primes ArrayList should be
	//   [23, 19, 17, 13, 11, 7, 5, 3, 2]
	public void buildPrimes(int n) {
		int start = (primes.size() == 0) ? 2 : primes.get(primes.size()-1) + 1;

		for (int i = start; i <= n; i++) {
			if (Main.isPrime(i)) primes.add(i);
		}
		// System.out.println(primes);
	}

	public int size() {
		return primes.size();
	}

	public int get(int n) {
		return primes.get(n);
	}

	public ArrayList<Integer> get() {
		return primes;
	}

	public String toString() {
		return "" + primes;
	}
}