Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Understanding this c++ code

  1. Mar 1, 2013 #1
    Hey guys. I just want to see if I am indeed "seeing" the significance of the code that is to follow. I will follow it with a brief explanation of what I thought the code did. Thanks in advance.


    PHP:

        const int N = 15;    
        bool table[N];

        int i = 0;
        while (i < N)
        {
            table[i] = true;
            i = i + 1;
        }

        table[0] = false;
        i = 2;
        while (i < N)
        {
            if (table[i])
            {
                int j = 2*i;

                while (j < N)
                {
                    table[j] = false;
                    j = j + i;
                }
            }
            i = i + 1;
        }

        i = 0;
        while (i < N)
        {
            if (table[i])
            {
                cout << i << " ";
            }
            i = i + 1;
        }
        cout << endl;

     
    This program scans through the program in accordance to properties exhibited by the integer value i. If the element in the array had a property being tracked, then it was assigned Boolean true. If it was not, then it was assigned Boolean false. This program demonstrates how one can scan through an array, pursuing a particular property, and henceforth convey which elements within that array had that property.
     
  2. jcsd
  3. Mar 1, 2013 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    You're missing the forest for the trees. This is a simple algorithm to find the prime numbers. It's called the sieve of Eratosthenes.
     
  4. Mar 1, 2013 #3
    That is the end result; but are any details in my explanation off?
     
  5. Mar 19, 2013 #4
    Well you have not explained what it does. It makes a table of numbers. It marks multiples of 2, then multiples of 3, then multiples of 4, then multiples of 5, etc. Eventually only prime numbers remain.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Understanding this c++ code
  1. Prime number code, C++ (Replies: 16)

  2. Critique my C++ code (Replies: 11)

Loading...