Class SieveOfEratosthenes
java.lang.Object
org.troy.capstone.data_structures.item_table.SieveOfEratosthenes
Code originally sourced from the MindTap assignment, but modified to be more memory efficient by using a BitSet to track which numbers are not prime, and to include a method for getting the largest prime under 100 million.
This Class implements the
Sieve of Eratosthenes algorithm to find prime numbers up to a set max value.-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionSieveOfEratosthenes(int maxValue) Constructor for theSieveOfEratosthenesclass, which initializes the sieve up to the specified maximum value. -
Method Summary
Modifier and TypeMethodDescriptionbooleanisPrime(int value) Checks if a given value is a prime number.Gets the largest prime number under 100 million using the Sieve of Eratosthenes algorithm.private voidReleases the internal array to be eligible for garbage collection.Gets the largest prime number under 100 million using the Sieve of Eratosthenes algorithm.
-
Field Details
-
notAPrime
A BitSet where the value at index i indicates whether i is not a prime number (true means not prime, false means potentially prime).
-
-
Constructor Details
-
SieveOfEratosthenes
public SieveOfEratosthenes(int maxValue) Constructor for theSieveOfEratosthenesclass, which initializes the sieve up to the specified maximum value.- Parameters:
maxValue- The maximum value up to which to calculate prime numbers. Must be a positive integer greater than or equal to 2.
-
-
Method Details
-
isPrime
public boolean isPrime(int value) Checks if a given value is a prime number.- Parameters:
value- The value to check for primality. Must be a non-negative integer.- Returns:
- true if the value is prime, false otherwise.
-
releaseMemory
private void releaseMemory()Releases the internal array to be eligible for garbage collection.- Postconditions:
isPrime()will throwNullPointerException.
-
staticPrimeUnder100mil
Gets the largest prime number under 100 million using the Sieve of Eratosthenes algorithm.- Returns:
- prime An
Optionalcontaining the largest prime number under 100 million, or empty if there was an error during calculation. - Postconditions:
isPrime()will throwNullPointerExceptiondue to memory release, as the sieve is no longer needed after finding the largest prime under 100 million.
-
maxPrimeUnder100mil
-