C++ Understanding the find_prime(bool prime[ ]) function below

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • whodgson
    Contributor
    • Jan 2007
    • 542

    C++ Understanding the find_prime(bool prime[ ]) function below

    The code below is part of the title fuction. What has been omitted is setting all elements from 2 to a user entered bound in prime[ ] to true and then setting all elements from j=2 to 2*j< bound to false thus ruling out all even numbers as prime. This last code finds all primes after 2 and before bound and works properly.
    [CODE=cpp]
    int p=3
    int p = 3;
    while (p<= bound/2)
    {
    for(int j=2;p*j<bound;j ++)
    prime [p*j] = false;//multiples of p are not prime
    do ++p;
    while(!prime[p]);
    };
    [/CODE]
    What i cannot understand is how the last line determines when p is again prime
    Last edited by weaknessforcats; Mar 30 '08, 11:27 PM. Reason: Fixed the code tags by removing spaces
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    Prime is an array of bools, yes? Thus, while(!prime[p]) is going to iterate until it reaches one that's false initially, so the ! makes it true.

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      Originally posted by Laharl
      Prime is an array of bools, yes? Thus, while(!prime[p]) is going to iterate until it reaches one that's false initially, so the ! makes it true.
      sorry i`m being so dumb but............ ..
      Yes its an array of bools all of which have been previously set to TRUE after which (and previously) all the even ones have been set to FALSE. So now all the odd ones (which are the only ones we are interested in) are set to TRUE.
      But i can`t see how it can evaluate a TRUE one and establish that it is FALSE and is therefore a prime without calling some function.
      I really don`t want to waste any more of your time so i`ll keep nagging away at it until some light appears. Its a matter of understanding what you have said above.
      thanks

      Comment

      Working...