scottca

Naive prime number filter chain

May 19th, 2014
197
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Naive prime number filter
  2.  * Inspired by Unix pipes, though these short circuit as soon as they detect a non-prime
  3.  */
  4. package primenumberfilterchain;
  5. public class PrimeNumberFilterChain {
  6.     public static void main(String[] args) {
  7.         int MAX_NUMBER = 10000;
  8.         Filter filter = new Filter(1); // not prime, but we need to start with something
  9.  
  10.         for (int i = 2; i <= MAX_NUMBER; i++) { //Note we start from 2, the first prime
  11.             if (filter.isPrime(i)) {
  12.                 System.out.println(i);
  13.             }
  14.         }
  15.     }
  16. }
  17.  
  18. class Filter {
  19.     int myMultiple;
  20.     Filter nextFilter;
  21.  
  22.     Filter(int number) {
  23.         myMultiple = number;
  24.         nextFilter = null;
  25.     }
  26.  
  27.     boolean isPrime(int number) {
  28.         if (myMultiple > 1 && (number % myMultiple == 0)) {
  29.             return false;
  30.         } else if (nextFilter != null) {
  31.             return nextFilter.isPrime(number);
  32.         } else {
  33.             nextFilter = new Filter(number);
  34.             return true;
  35.         }
  36.     }
  37. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×