C/C++ Finding Primes Using the Sieve of Eratosthenes

  • Thread starter Thread starter SaRaH...
  • Start date Start date
  • Tags Tags
    Primes
AI Thread Summary
The discussion revolves around implementing the Sieve of Eratosthenes algorithm to find prime numbers between 0 and n using bit manipulation and bit arrays. The user has a theoretical understanding but struggles with coding, particularly in finding the first bit set to 1 and clearing multiples of found primes. Key steps in the algorithm include initializing an array of bits, setting the first two bits to zero, and iterating through the array to identify prime numbers. Issues highlighted include a precedence problem in the bitwise operations, where the user initially misapplied the operator precedence, leading to incorrect checks for set bits. Suggested corrections involve using proper parentheses to ensure the correct evaluation of expressions. Additionally, there's a lack of implementation for clearing bits corresponding to multiples of identified primes, which is crucial for the algorithm's success. The discussion emphasizes the importance of understanding bit manipulation in C/C++ and the need for clear operator precedence in coding practices.
SaRaH...
Messages
7
Reaction score
0
I have been trying to write a program whose function is to find all of the prime numbers between 0 and n using the "Sieve of Eratosthenes" method. (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) using bit manipulation and bit arrays and the print out the number of primes found, the first five primes and the last five primes. I understand in theory exactly how this works however am having trouble converting that understanding into code. It has to be done using an array of bits which is the problem.

The main steps are as follows:
1. Set the bits representing 0 and 1 to zero and all remaining bits to one. 2. Set count to 0 (the number of found primes so far).
3. Find the first bit in the array that is 1 and assign the value it represents to p (this is a prime number) and increment count.
4. Clear all bits in the array corresponding to multiples of p.
5. Repeat the last two steps until p^2 > n (need to continue until p^2 > n so that the number of primes < N is calculated correctly).

All bits in the array that still have a value of 1 correspond to the prime numbers.

I think I have managed to carry out step one correctly however am now not quite sure how to find the the first bit that has the value of 1 and how to continue from there.

This is a link to the full problem but I'm not certain if it'll work. If not I can post the text:
http://www.scss.tcd.ie/Ivana.Dusparic/2E...b/Lab2.pdf
Any help would be much appreciated.

Code:
#define N 100000000 // size of sieve used
#define SIZE ((N+31)/32) //32 bits per integer hard coded
int sieve[SIZE]; //declare array of bits
int count; // count number of primes found

#include <iostream>
#include <iomanip>
#include <time.h>
using namespace std;


void main() {
    int t = clock();

    int array_element;
    int div_result;
    int count=0;

     for(int i = 0; i < SIZE; i++) {
              sieve[i] = 0xFFFFFFFF;                //sets all bits to 1
           }


    sieve[0] = 0xFFFFFFFC;                               //sets first 2 bits to 0


     for (int j = 0; j < SIZE; j++) {                     //loops through each element of the array

         array_element = sieve[j];

         for (int k = 0; k <= 31; k++) {             //loops through each bit of each element of array?               
                
             if (j&1<<k==1) {                       //checks if bit is 1?
                 int p = k;                            //assigns the the bit number to p?
                 cout << p;                          //prints out the bit number?

             }
         }
     }


    cout << "Number of primes less than 100, 000, 000 = " << count << "\n";

    cout << "first 5 primes \n";

    cout << "last 5 primes \n";



      cout << "runtime = " << fixed << setprecision(3) << (double) (clock() - t) / CLOCKS_PER_SEC <<
"s" << endl;
}
 
Last edited by a moderator:
Technology news on Phys.org
SaRaH... said:
Code:
             if (j&1<<k==1) {                       //checks if bit is 1?
There's a precedence issue. Although the binary and operator "&" should have had the same precendence as multiply "*", instead it was given a very low precedence, lower than logical comparasons (which doesn't make sense). The other issues are you want to use array_element, not j, and you're checking for a bits in various positions other than 0:

Code:
             if ((array_element & (1<<k)) != 0) {   //checks if bit is 1?

An alternative is:

Code:
             if ((array_element>>k) & 1) == 1) {   //checks if bit is 1?

I don't see any code that goes through the sieve to clear out bits that are multiples of prime numbers.
 
So rather than using the for loop that I had:

Code:
for (int k = 0; k <= 31; k++) {
				
			 /*if (j&1<<k==1) {
				 int p = k;
				 cout << p;*/
                            }
}

Would it make more sense to use something like this?

Code:
for (int k = 0; k <= 31; k++) {if ((array_element & (1<<k)) != 0) {
				 int p = k;
				 if (k != 0) {
					 array_element == 0;
					 cout << p;
				 }

}

Sorry I'm just really not sure where I'm going with this at all as we have never covered it at all and I can't find very much information about it either on the internet or in books. I could do it using an integer array, I'm just struggling to understand how to represent, find and change each bit it code.
 
rcgldr said:
There's a precedence issue. Although the binary and operator "&" should have had the same precendence as multiply "*", instead it was given a very low precedence, lower than logical comparasons (which doesn't make sense).
That it doesn't make any sense is your opinion; it obviously is not the opinion of the standards committee. The standards committee's opinion is the only one that counts; we are stuck with the rules they came up with.

There is of course an out: Use parentheses. Many projects augment the C/C++ precedence table with a rather simple rule: Except for multiplication over addition/subtraction, code that relies the C/C++ precedence rules is invalid code. Always use parentheses.
 
rcgldr said:
Although the binary and operator "&" should have had the same precendence as multiply "*", instead it was given a very low precedence, lower than logical comparasons (which doesn't make sense).

D H said:
That it doesn't make any sense is your opinion.
Not just mine:

The logical bitwise operators in C (and all programming languages that borrowed precedence rules from C, for example, C++, Perl and PHP) have a precedence level that the author of the language considers to be unsatisfactory.

http://en.wikipedia.org/wiki/Order_of_operations#Programming_languages

Kernighan and Ritchie say ... Some of the operators have the wrong precedence

Some questionable choices of operator precedence, as mentioned by Kernighan and Ritchie above, such as == binding more tightly than & and | in expressions like x & 1 == 0, which would need to be written (x & 1) == 0 to be properly evaluated.

http://en.wikipedia.org/wiki/C_(programming_language)#Syntax

Always use parentheses.
Yes, virtually all programmers will agree with this.
 
Last edited:
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top