Click here to Skip to main content
15,896,153 members
Articles / Programming Languages / C#

Find Prime Numbers in C# Using the Sieve of Eratosthenes

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
20 Sep 2011CPOL 14.1K  
This solution uses half the space by simply ignoring all even numbers. It will require a little index calculation. Also, primes are generated one by one instead of returning a list.Another optimization can be made by starting the crossing out of multiples of a prime p at p2. Any smaller number...

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

Please Sign up or sign in to vote.
12 Sep 2011Bill Anderson
Here's an alternative. This one uses the BitArray class in C# and does not use the % operator.static List SeiveWithoutMod(int candidate){ BitArray sieveContainer = new BitArray(candidate + 1, true); int marker = 2; //start int factor = 2; //start. sieveContainer[0]...
Please Sign up or sign in to vote.
30 Sep 2011Bill Anderson
Hi,Thanks for the feedback for alternative #1 from above (and thank you, Jurgen Rohr for your suggestion! I replaced the "reset" line with:while (!sieveContainer.Get(++marker));factor = marker;Here is another algorithm that's slightly different. It's not as elegant an approach, but...
Please Sign up or sign in to vote.
3 Oct 2011Brian C Hart 4 alternatives  
This tip illustrates a simple C# console program that uses the Sieve of Eratosthenes algorithm to quickly find prime numbers.
Please Sign up or sign in to vote.
12 Sep 2011George Swan
The following method starts by selecting the number 2 and eliminates each multiple of 2 up to N. Then the next valid number is selected and each multiple of it is eliminated. The process is repeated until all valid numbers have been tested. So the first three multiples to be eliminated are...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
Netherlands Netherlands
Software developer with a bachelor degree and a few years experience (studied computer science at a university as well, but didn't finish). Really love C#, but work usually involves Java. Some experience with VB and C as well.

When hobbying I almost exclusively use C# and AutoHotkey. In a previous life I did some Haskell and Modula-3 and similar stuff. I enjoy games and solving puzzles like on http://projecteuler.net/ (I think I'm stuck at level 4, though)

Comments and Discussions