Advertisement
cd62131

Prime Number

Dec 9th, 2013
392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.41 KB | None | 0 0
  1. import java.util.Iterator;
  2. import java.util.SortedSet;
  3. import java.util.TreeSet;
  4.  
  5. public class Prime implements Iterable<Long> {
  6.   private final SortedSet<Long> primes;
  7.  
  8.   public Prime() {
  9.     primes = new TreeSet<Long>();
  10.     primes.add((long )2);
  11.     primes.add((long )3);
  12.   }
  13.  
  14.   public SortedSet<Long> primes() {
  15.     return primes;
  16.   }
  17.  
  18.   public boolean isPrime(long n) {
  19.     for (long i = primes().last() + 2; i <= n; i += 2) {
  20.       boolean is_prim = true;
  21.       for (long j: primes()) {
  22.         if (i % j == 0) {
  23.           is_prim = false;
  24.           break;
  25.         }
  26.       }
  27.       if (is_prim) primes().add(i);
  28.     }
  29.     for (long i: primes())
  30.       if (n % i == 0) return false;
  31.     return true;
  32.   }
  33.  
  34.   @Override
  35.   public Iterator<Long> iterator() {
  36.     return primes.iterator();
  37.   }
  38.  
  39.   private static void print(Prime p) {
  40.     int i = 0;
  41.     StringBuilder sb = new StringBuilder();
  42.     Iterator<Long> it = p.primes().iterator();
  43.     while (it.hasNext()) {
  44.       sb.append(it.next());
  45.       if (it.hasNext()) sb.append(" ");
  46.       if (++i % 20 == 0) sb.append("\n");
  47.     }
  48.     System.out.println(sb.toString());
  49.   }
  50.  
  51.   public static void main(String[] args) {
  52.     Prime p = new Prime();
  53.     print(p);
  54.     if (p.isPrime(100)) System.out.println("100 is prime number.");
  55.     print(p);
  56.     if (p.isPrime(1000)) System.out.println("1000 is prime number.");
  57.     print(p);
  58.   }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement