简体   繁体   中英

Java - Prime Number Algorithm Implementation doesn't work

I wrote this code which is supposed to search for prime numbers and put them into an array. Here it is:

int[] prime_array = new int[(int)s.upper_bound];
int index_in_array = 0;
boolean are_we_done = false;
int index = 1;
boolean is_prime = true;

while (!are_we_done) {
    try {
        for (int i = 1; i < index; i++) {
            if ((index%i)==0) {
                is_prime = false;
            }
        }

        if (is_prime) {
            prime_array[index_in_array] = index;
            index_in_array++;
        }

        index++;
        is_prime = true;
    } 
    catch (IndexOutOfBoundsException e) {
        are_we_done = true;
        break;
    }
}

Unfortunately, the only prime it catches is 1. Any idea why it doesn't work?

Your for loop is looking for factors starts with i=1 , and if index%i==0 you decide it is not a prime. But n%1==0 for all integers n .

The lowest factor that indicates that something is not prime is 2 .

Edit:

Here are some other suggestions:

  • Use a properly bounded loop to cycle through your candidate primes.
  • Only check factors up to the square root of the candidate prime.
  • Only check 2 and odd numbers as primes (because no even number above 2 is prime, and 1 is a unit, not a prime)
  • Only check 2 and odd numbers as factors (because no even number above 2 can be a prime factor)
  • Use a sieve instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM