java - Primes and boolean logic -


i wanted write program find primes b wrote code (which worked):

public static void main(string[] args) {         int a;     int c;     boolean isprime;      = 2;     c = 0;      while(a <= 100000 ){         isprime = true;         (int b = 2;b<a; b++){             c = a%b ;              //system.out.println(c);              if ( c == 0){                 // stores every not prime number                 isprime = false;                                         }                                    }          if (isprime){             system.out.println(a);         }                    a=a+1;       }                                    } // main end 

next tried write variation of code, 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;         (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 me first , second codes similar. difference (i see) initialized isprime true in first one, , false in second one.

why first code work , second not?

the 2 code examples similar, opposite in initializations , handling of isprime , isprimeone variables.

the first code assumes number prime (true) until factor found. proves number composite, it's set false , stays way until loop finishes. 1 factor needed prove it's composite.

however, second code assumes number composite (false) until number found isn't factor. because number found not factor doesn't mean it's prime. e.g. 20 doesn't have 3 factor, it's still composite. printing w, remainder, instead of q, number you're testing. incrementing w instead of q, , outside while loop instead of inside while loop.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -