I wanted to write a program to find all the primes from b to a so I wrote this code (which worked):
public static void main(String[] args) {
int a;
int c;
boolean isPrime;
a = 2;
c = 0;
while(a <= 100000 ){
isPrime = true;
for (int b = 2;b<a; b++){
c = a%b ;
//System.out.println(c);
if ( c == 0){
// this stores every not prime number
isPrime = false;
}
}
if (isPrime){
System.out.println(a);
}
a=a+1;
}
} // main end
Next I tried to write a variation of this code, which did not work:
public static void main(String[] args) {
int q;
int w;
boolean isPrimeOne = false;
q = 2;
w = 0;
while(q <= 100){
isPrimeOne = false;
for (int d = 2; d<q; d++){
w = q%d;
if( w != 0 ){
isPrimeOne = true;
}
}
}
if(isPrimeOne){
System.out.println(w);
}
w = w+1;
}
It seems to me like my first and second codes are very similar. The only difference (I see) is that I initialized isPrime
as true
in the first one, and as false
in the second one.
Why does the first code work and the second does not?
The 2 code examples are similar, but they are opposite in the initializations and handling of the
isPrime
andisPrimeOne
variables.The first code assumes that a number is prime (
true
) until a factor is found. That proves the number is composite, so it's set tofalse
and it stays that way until the loop finishes. Just one factor is needed to prove that it's composite.However, the second code assumes that a number is composite (
false
) until a number is found that isn't a factor. But just because a number was found not to be a factor doesn't mean that it's prime. E.g.20
doesn't have3
as a factor, but it's still composite. You are printingw
, the remainder, instead ofq
, the number you're testing. You are incrementingw
instead ofq
, and that is outside thewhile
loop instead of inside thewhile
loop.