I donโ€™t quite understand what my lecturer is doing here - lecture notes on calculating primes with Java

A naive algorithm for calculating prime numbers numbers exist. For example, you could use a while loop to check that c% i! = 0 for all positive integers such that i> 1 and i <s.

However, it is not difficult to understand that a much better method guarantees that c% p! = 0 for all primes p such that p <c. Using primes in your ArrayList is as easy as pie. Once again, this suggests that you are using a time loop.

I tried to implement both of these methods, and while I get the first, checking that c% i! = 0, I donโ€™t understand the second part of the information saying that using c% p! = 0 would be the best algorithm. Doesn't that mean that would I have to know all the primes in order to calculate a prime number?

I currently have the following:

  public static void isPrime(int candidateNo) {
while (i <= candidateNo/2) {
  if (candidateNo%i==0 && i!=1) {
    return false;
  }
  else
    return true;
}

}

which works, although inefficient. I use a function to create arraylist primes (if the function returns true, the number is added to the arraylist).

+3
source share
2 answers

Well, since you still create a list of all primes, when you check if c is a prime, you already have all the smaller primes in your list. Correctly?

, , , - candidateNo/2 , , - candidateNo/2 .

, i = 2 to candidateNo/2 . , , isPrime, , .

+5

, , .

:

15 = 3 * 5
24 = 2 * 2 * 2 * 3
0

Source: https://habr.com/ru/post/1777507/


All Articles