aboutsummaryrefslogtreecommitdiff
path: root/sem5/oop/m2/primes/src/PrimeGen.java
blob: 9c91645b5952a4351c633e58651cbb6885333328 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.io.PrintStream;
import java.util.ArrayList;

public class PrimeGen {
	
	private ArrayList<Integer> primes;
	private int at;

	public PrimeGen() {
		this.primes = new ArrayList<>();
		
		this.at = 1;
	}
	
	public int next(int limit) {
		// Run until a prime
		primeloop:
		while (true) {
			this.at++;
			if (this.at >= limit) {
				return -1;
			}

			for (int prime : this.primes) {
				if (this.at % prime == 0) {
					continue primeloop;
				}
			}
			break;
		}
	
		this.primes.add(at);
		return at;
	}
	
	public int next() {
		return next(-1);
	}
	
}