7

I know there is one which is used in all kind of .NET dictionaries and hashtables in:

internal static class HashHelpers

  • Is there a public one somwhere else as well?
  • If no, why is it kept internal isn't it something very commonly used?
  • Is the copy & paste the way to go if I need prime numbers in my code?
George Mamaladze
  • 7,593
  • 2
  • 36
  • 52

2 Answers2

5
  1. As far as I know, there is no public version of that table available in .NET
  2. Because this table is not a table of all prime numbers in a range, but rather a table of arbitrarily chosen subset of prime numbers suitable for a particular purpose (sizing hash-based containers)
  3. No, you should either generate your own table on the fly, or copy-paste a table from one of many complete sources.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

I cannot answer your question regarding the availability of HashHelpers, but here are ways of implementing it yourself.

Here a post with some imperative implementations on generating prime numbers: Most elegant way to generate prime numbers

Additionally, you can do it in LINQ:

var odds =
    from n in Enumerable.Range(0, int.MaxValue)
    select 3 + (long) n * 2;

var primes = (new[] { 2L }).Concat(
    from p in odds
    where ! odds.TakeWhile(odd => odd * odd <= p).Any(odd => p % odd == 0)
    select p);

Source: http://jacobcarpenter.wordpress.com/2008/03/26/linq-to-prime-numbers/

Edit: Don't use int.MaxValue in your initial range. Limit this to something appropriate.

Community
  • 1
  • 1
Dave New
  • 38,496
  • 59
  • 215
  • 394
  • This is one of the most beautiful piece of code to generate primes that I've seen, but it is definitely not the most performant. It performs far more checks than it needs to. A better alternative would be to use only the primes that we've already found as candidate divisors. – Sergey Kalinichenko Jul 30 '12 at 11:28
  • The question was not about "how to generate prime numbers in .net" - the main point of my question was **having a table of precalculeted primes** to use in hasing, encyption etc. algorithms - in order to save time for their calculation. – George Mamaladze Jul 30 '12 at 11:34
  • 2
    @achitaka-san - if you can generate the primes it's pretty trivial to put them in a static array. If you want, you can even write them into a text file [formatted as a C# array] than C&P this into your code file. THINK MAN THINK! – NPSF3000 Jul 30 '12 at 11:41