Lady_Aleena, the Sieve of Eratosthenes is a well-known approach to generating primes. To illustrate, suppose you want to generate the primes between 2 and 20 (as neither 0 and 1 are prime, by definition).

  1. Write out the list of numbers from 2 to 20 (this johngg does by creating a vector, with the bits for 0 and 1 set to 1):
    As numbers: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
    As vector: 110000000000000000000
    Position:  000000000011111111112
               012345678901234567890
  2. For each number not marked off the list, mark off its multiples (johngg does this by setting that bit of the vector to '1'):
    1. For 2:
      As numbers: 0 1  2 3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20 
      As vector: 110010101010101010101
      Position:  000000000011111111112
                 012345678901234567890
    2. For 3:
      As numbers: 0 1 2 3  4  5  6  7  8 9 10  11  12  13  14 15 16  17  18  19  20 
      As vector: 110010101110101110101
      Position:  000000000011111111112
                 012345678901234567890

    Because the square root of 20 is approximately 4.5, we don't have to try the exercise with values beyond 5; thus our list of primes would be:

    2 3 5 7 11 13 17 19
    As vector: 110010101110101110101
    Position:  000000000011111111112
               012345678901234567890
    The vector bits at 2, 3, 5, 7, 11, 13, 17, and 19 are not set (0), indicating those values are prime.

Hope that helps.

Update: 2015-04-01
Updated formatting of example lines to highlight overstrike of values.


In reply to Re^5: Number functions I have lying around by atcroft
in thread Number functions I have lying around by Lady_Aleena

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.