Files
JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java
2021-06-30 17:52:08 -04:00

86 lines
2.6 KiB
Java

//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 06-30-21
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package mattrixwv;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class SieveOfEratosthenesBig implements Iterator<BigInteger>{
BigInteger possiblePrime;
private Map<BigInteger, ArrayList<BigInteger>> dict;
public SieveOfEratosthenesBig(){
dict = new HashMap<BigInteger, ArrayList<BigInteger>>();
possiblePrime = BigInteger.TWO;
}
@Override
public boolean hasNext(){
return true;
}
@Override
public BigInteger next(){
BigInteger prime;
if(possiblePrime.compareTo(BigInteger.TWO) > 0){
//Loop until you find a prime number
for(;dict.containsKey(possiblePrime);possiblePrime = possiblePrime.add(BigInteger.TWO)){
//Create the next entry for all entries in the map
for(BigInteger num : dict.get(possiblePrime)){
BigInteger loc = possiblePrime.add(num).add(num);
if(!dict.containsKey(loc)){
ArrayList<BigInteger> tempArray = new ArrayList<BigInteger>(Arrays.asList(num));
dict.put(loc, tempArray);
}
else{
dict.get(loc).add(num);
}
}
//Delete the current entry
dict.remove(possiblePrime);
}
//Save that the number is a prime
prime = possiblePrime;
BigInteger loc = prime.multiply(BigInteger.valueOf(3));
if(!dict.containsKey(loc)){
ArrayList<BigInteger> tempArray = new ArrayList<BigInteger>(Arrays.asList(prime));
dict.put(loc, tempArray);
}
else{
dict.get(loc).add(prime);
}
//Move on to the next possible prime
possiblePrime = possiblePrime.add(BigInteger.TWO);
}
else{
//Return 2 and move to 3
prime = possiblePrime;
possiblePrime = possiblePrime.add(BigInteger.ONE);
}
return prime;
}
}