Added the things that the added the things.
The things.
This commit is contained in:
@@ -1,15 +1,63 @@
|
|||||||
package arrays;
|
package arrays;
|
||||||
|
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
|
import java.util.Queue;
|
||||||
import tester.Tester;
|
import tester.Tester;
|
||||||
|
|
||||||
class Sieve implements Iterator<Integer> {
|
class Sieve implements Iterator<Integer> {
|
||||||
|
int cur; // The current number.
|
||||||
|
int lim; // The largest number to check.
|
||||||
|
boolean[] isntPrime; // Where true, not a prime.
|
||||||
|
|
||||||
public boolean hasNext() { return false; }
|
Sieve(int lim) {
|
||||||
|
if (lim < 2)
|
||||||
|
throw new UnsupportedOperationException(
|
||||||
|
"Can't find primes less than 2."
|
||||||
|
);
|
||||||
|
|
||||||
public Integer next() { return null; }
|
this.cur = 2; // Start with 2.
|
||||||
|
this.lim = lim;
|
||||||
|
this.isntPrime = new boolean[lim + 1];
|
||||||
|
|
||||||
|
this.isntPrime[3] = true;
|
||||||
|
|
||||||
|
/*
|
||||||
|
for (int i = this.cur; i <= this.lim; i += this.cur) {
|
||||||
|
this.isntPrime[i] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = this.cur; !this.isntPrime[i]; i++) {}
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
// [ false false false false false false false ]
|
||||||
|
// [ 1 2 3 4 5 6 7 ]
|
||||||
|
//
|
||||||
|
// [ false false false false false false false ]
|
||||||
|
// [ 1 2 3 4 5 6 7 ]
|
||||||
|
|
||||||
|
public boolean hasNext() { return true; }
|
||||||
|
|
||||||
|
public Integer next() {
|
||||||
|
while (this.isntPrime[this.cur]) this.cur++;
|
||||||
|
return this.cur;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Examples {
|
class Examples {
|
||||||
Iterator<Integer> i = new Sieve();
|
void testSieve(Tester t) {
|
||||||
|
Sieve sieve = new Sieve(10);
|
||||||
|
t.checkExpect(sieve.hasNext(), true);
|
||||||
|
t.checkExpect(sieve.next(), 2);
|
||||||
|
t.checkExpect(sieve.next(), 3);
|
||||||
|
t.checkExpect(sieve.next(), 5);
|
||||||
|
t.checkExpect(sieve.next(), 7);
|
||||||
|
t.checkExpect(sieve.next(), 11);
|
||||||
|
t.checkExpect(sieve.next(), 13);
|
||||||
|
t.checkExpect(sieve.next(), 17);
|
||||||
|
t.checkExpect(sieve.next(), 19);
|
||||||
|
t.checkExpect(sieve.next(), 23);
|
||||||
|
t.checkExpect(sieve.next(), 29);
|
||||||
|
t.checkExpect(sieve.next(), false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user