What is the significance of this C++ code and what does it do?

  • Topic: C/C++ 
  • Thread starter Thread starter sandy.bridge
  • Start date Start date
  • Tags Tags
    C++ Code
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
3 replies · 3K views
sandy.bridge
Messages
797
Reaction score
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])
		{
			count << i << " ";
		}
		i = i + 1;
	}
	count << 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.
 
Physics news on Phys.org
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.
 
That is the end result; but are any details in my explanation off?
 
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.