Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Iterator;
- import java.util.SortedSet;
- import java.util.TreeSet;
- public class Prime implements Iterable<Long> {
- private final SortedSet<Long> primes;
- public Prime() {
- primes = new TreeSet<Long>();
- primes.add((long )2);
- primes.add((long )3);
- }
- public SortedSet<Long> primes() {
- return primes;
- }
- public boolean isPrime(long n) {
- for (long i = primes().last() + 2; i <= n; i += 2) {
- boolean is_prim = true;
- for (long j: primes()) {
- if (i % j == 0) {
- is_prim = false;
- break;
- }
- }
- if (is_prim) primes().add(i);
- }
- for (long i: primes())
- if (n % i == 0) return false;
- return true;
- }
- @Override
- public Iterator<Long> iterator() {
- return primes.iterator();
- }
- private static void print(Prime p) {
- int i = 0;
- StringBuilder sb = new StringBuilder();
- Iterator<Long> it = p.primes().iterator();
- while (it.hasNext()) {
- sb.append(it.next());
- if (it.hasNext()) sb.append(" ");
- if (++i % 20 == 0) sb.append("\n");
- }
- System.out.println(sb.toString());
- }
- public static void main(String[] args) {
- Prime p = new Prime();
- print(p);
- if (p.isPrime(100)) System.out.println("100 is prime number.");
- print(p);
- if (p.isPrime(1000)) System.out.println("1000 is prime number.");
- print(p);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement