Advertisement
duc-phan

Untitled

Nov 30th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.29 KB | None | 0 0
  1. /**
  2.  * This class Generates prime numbers up to a user specified
  3.  * maximum. The algorithm used is the Sieve of Eratosthenes.
  4.  * Given an array of integers starting at 2:
  5.  * Find the first uncrossed integer, and cross out all its
  6.  * multiples. Repeat until there are no more multiples
  7.  * in the array.
  8.  */
  9. public class PrimeGenerator
  10. {
  11.     private static boolean[] crossedOut;
  12.     private static int[] result;
  13.     public static int[] generatePrimes(int maxValue)
  14.     {
  15.         if (maxValue < 2)
  16.             return new int[0];
  17.         else
  18.         {
  19.             uncrossIntegersUpTo(maxValue);
  20.             crossOutMultiples();
  21.             putUncrossedIntegersIntoResult();
  22.             return result;
  23.         }
  24.     }
  25.     private static void uncrossIntegersUpTo(int maxValue)
  26.     {
  27.         crossedOut = new boolean[maxValue + 1];
  28.         for (int i = 2; i < crossedOut.length; i++)
  29.             crossedOut[i] = false;
  30.     }
  31.     private static void crossOutMultiples()
  32.     {
  33.         int limit = determineIterationLimit();
  34.         for (int i = 2; i <= limit; i++)
  35.             if (notCrossed(i))
  36.                 crossOutMultiplesOf(i);
  37.     }
  38.     private static int determineIterationLimit()
  39.     {
  40.     // Every multiple in the array has a prime factor that
  41.     // is less than or equal to the root of the array size,
  42.     // so we don't have to cross out multiples of numbers
  43.     // larger than that root.
  44.         double iterationLimit = Math.sqrt(crossedOut.length);
  45.         return (int) iterationLimit;
  46.     }
  47.     private static void crossOutMultiplesOf(int i)
  48.     {
  49.         for (int multiple = 2*i;
  50.              multiple < crossedOut.length;
  51.              multiple += i)
  52.             crossedOut[multiple] = true;
  53.     }
  54.     private static boolean notCrossed(int i)
  55.     {
  56.         return crossedOut[i] == false;
  57.     }
  58.     private static void putUncrossedIntegersIntoResult()
  59.     {
  60.         result = new int[numberOfUncrossedIntegers()];
  61.         for (int j = 0, i = 2; i < crossedOut.length; i++)
  62.             if (notCrossed(i))
  63.                 result[j++] = i;
  64.     }
  65.     private static int numberOfUncrossedIntegers()
  66.     {
  67.         int count = 0;
  68.         for (int i = 2; i < crossedOut.length; i++)
  69.             if (notCrossed(i))
  70.                 count++;
  71.         return count;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement