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?