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:
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.