c# - Most elegant way to generate prime numbers -


What is the best way to implement this function:

  ArrayList generPrime (int N)  

This function generates first n primes (edit: where n> 1 ), so Returns {2, 3, 5, 7, 11} with generPrimes (5) ArrayList . (I'm doing it in C #, but I'm happy with Java implementation - or any other similar language for that language (not hackel)).

I know how to write this function, but when I did it last night, it was not as good as expected. Here is who I came with:

  ArrayList Generate Prime (int to generate) {ArrayList primes = new ArrayList (); Primes.Add (2); Primes.Add (3); While (primes.Count & lt; toGenerate) {int nextPrime = (int) (primes [primes.Count - 1]) + 2; While (true) {bool isPrime = true; Foreach (int n in primes) {if (nextPrime% n == 0) {isPrime = false; break; }} If (isPrime) {break; } Else {nextPrime + = 2; }} Primes.Add (nextPrime); } Return Primes; }  

I am not very worried about speed, although I do not want it to be clearly disabled. I do not care what method is used (simple or sieve or something), but I want it to be quite less and clear how it works.

Edit : Thanks everyone who answered, though many did not answer my actual question. To be replicated, I need a clean code code that prepares a list of main numbers I already know how to do it differently, but I want to write a code that is not clearly It is as it can be. Some good options have been proposed in this thread:

  • A good version of what I originally had (Peter Smit, Jmservera and Rekreativc)
  • A very clean implementation Eratostenes (Starbull) sieve
  • Use Java's BigEngiger s and NextProfilePrem for very simple code, although I find it particularly efficient Deaf
  • To generate a list of primers to use LINQ
  • One Put a lot of prime in the text file and read them when necessary (Darin)

Edit 2 : I have some methods here, and another The method is not mentioned here. They can first find the n prime effectively (and I have a search for the limit to provide to the CEO).

use the estimate

  pi (n) = n / log (n)  

for the number of primes A. To find a range N, and then use a sieve to estimate reduces somewhat the number of projected numbers, so will be slightly larger than the sieve required, which is fine.

This is going to be my standard Java, about a million calculates the first million primes a normal laptop:

  Public static bitset compressed premium (complete) Border) {last bitset primes = new bitset (); Primes.set (0, False); Primes.set (1, Incorrect); Primes.set (2, boundary, true); For (Int i = 0; i * i; limit; i ++) {if (primes.get (i)) {for (int j = i * i; j & lt; limit; j + = i ) {Primes.clear (j); }}} Returns Primes; }  

Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -