A naive algorithm for computing prime
numbers exists. For example, you could
use a while loop to check that c % i
!= 0 for all positive integer i such
that i > 1 and i < c.However, it is
not dicult to see that a much better
method is making sure that c % p != 0
for all prime numbers p such that p <
c. Using the primes in your ArrayList
this is easy as pie. Note again that
this suggests that you use a while
loop.
I’ve tried to implement both of these methods, and while I get the first one, checking that c % i != 0, I don’t understand the second piece of information saying a better algorithm would be to use c % p !=0. Would this not mean I would have to know all prime numbers to compute the prime number ?
What I have at the moment is as follows :
public static void isPrime(int candidateNo) {
while (i <= candidateNo/2) {
if (candidateNo%i==0 && i!=1) {
return false;
}
else
return true;
}
}
which works, though is woefully inefficient. I am using the function to create an arraylist of prime numbers (if the function returns true, the number is added to the arraylist).
Well, since you are creating a list of all the prime numbers anyway, when you check if a number c is prime, you already have all smaller prime numbers in your list. Right?
So, instead of testing if any number smaller than
candidateNo/2divides your candidate, you only test if any prime number smaller thancandidateNo/2divides your candidate.So, instead of iterating from
i = 2 to candidateNo/2, you iterate over the elements of your array list. To this end, this array list should of course be accessible from your isPrime function, so either pass it as an argument or have it as a public static element of your main class.