Advertisement
duc-phan

Untitled

Nov 30th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.19 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.  * <p>
  5.  * Eratosthenes of Cyrene, b. c. 276 BC, Cyrene, Libya --
  6.  * d. c. 194, Alexandria. The first man to calculate the
  7.  * circumference of the Earth. Also known for working on
  8.  * calendars with leap years and ran the library at Alexandria.
  9.  * <p>
  10.  * The algorithm is quite simple. Given an array of integers
  11.  * starting at 2. Cross out all multiples of 2. Find the next
  12.  * uncrossed integer, and cross out all of its multiples.
  13.  * Repeat untilyou have passed the square root of the maximum
  14.  * value.
  15.  *
  16.  * @author Alphonse
  17.  * @version 13 Feb 2002 atp
  18.  */
  19. import java.util.*;
  20. public class GeneratePrimes
  21. {
  22.     /**
  23.      * @param maxValue is the generation limit.
  24.      */
  25.     public static int[] generatePrimes(int maxValue)
  26.     {
  27.         if (maxValue >= 2) // the only valid case
  28.         {
  29.             // declarations
  30.             int s = maxValue + 1; // size of array
  31.             boolean[] f = new boolean[s];
  32.             int i;
  33.             // initialize array to true.
  34.             for (i = 0; i < s; i++)
  35.                 f[i] = true;
  36.             // get rid of known non-primes
  37.             f[0] = f[1] = false;
  38.             // sieve
  39.             int j;
  40.             for (i = 2; i < Math.sqrt(s) + 1; i++)
  41.             {
  42.                 if (f[i]) // if i is uncrossed, cross its multiples.
  43.                 {
  44.                     for (j = 2 * i; j < s; j += i)
  45.                         f[j] = false; // multiple is not prime
  46.                 }
  47.             }
  48.             // how many primes are there?
  49.             int count = 0;
  50.             for (i = 0; i < s; i++)
  51.             {
  52.                 if (f[i])
  53.                     count++; // bump count.
  54.             }
  55.             int[] primes = new int[count];
  56.             // move the primes into the result
  57.             for (i = 0, j = 0; i < s; i++)
  58.             {
  59.                 if (f[i]) // if prime
  60.                     primes[j++] = i;
  61.             }
  62.             return primes; // return the primes
  63.         }
  64.         else // maxValue < 2
  65.             return new int[0]; // return null array if bad input.
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement