Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package fromLeonard;
- import java.util.ArrayList;
- /**
- * Creates a list of primes. Starts with 1, ends with a number specified in the
- * constructor.
- *
- * @author Pi-Nerd Fisher
- * @version 2.0
- */
- public class Primes {
- // instance fields
- private ArrayList<Integer> foo = new ArrayList<Integer>();
- private ArrayList<Integer> primes = new ArrayList<Integer>();
- private int limit;
- private static int LOWEST_PRIME = 2;
- // constructor
- /**
- * Creates a list of primes from 2 to limit.
- *
- * @param limit
- * The largest number to look for primes in.
- */
- public Primes(int limit) {
- this.limit = limit;
- fillList(LOWEST_PRIME);
- getPrimes();
- }
- // methods
- private void fillList(int start) {
- for (int i = start; i <= limit; i++) {
- this.foo.add(i);
- }
- }
- private void getPrimes() {
- while (!foo.isEmpty()) {
- if (primes.isEmpty()) {
- primes.add(foo.get(0));
- foo.remove(0);
- } else {
- if (checkPrime(foo.get(0), 0)) {
- primes.add(foo.get(0));
- foo.remove(0);
- } else {
- foo.remove(0);
- }
- }
- }
- }
- private boolean checkPrime(int bar, int j) {
- while (j < primes.size()) {
- if (bar % primes.get(j) == 0) {
- return false;
- } else {
- j++;
- }
- }
- return true;
- }
- /**
- * Gets the list of all primes lower than the number in the constructor.
- *
- * @return an ArrayList with primes
- */
- public ArrayList<Integer> getList() {
- return primes;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement