PDA

Click to See Complete Forum and Search --> : IsPrime in C#


Kasracer
Dec 29th, 2005, 09:13 AM
This might be useful to someone out there.

This function takes in an integer (32bit but you shouldn't need to worry about that). Then, it uses The Sieve of Eratosthenes method to find out if the number supplied to it is a prime number or not. It's very quick compared to conventional methods.

I was working on this function and found this article (http://www.codeproject.com/csharp/highspeed_primenumbers.asp) to optimize it using the Sieve of Eratosthenes method.

This function may not be that useful to anyone but I thought I would throw it in here.

public static bool IsPrime(Int32 ToBeChecked)
{
System.Collections.BitArray numbers = new System.Collections.BitArray(ToBeChecked+1, true);
for (Int32 i = 2; i < ToBeChecked+1; i++)
if (numbers[i])
{
for (Int32 j = i * 2; j < ToBeChecked+1; j += i)
numbers[j] = false;
if (numbers[i])
{
if (ToBeChecked == i)
{
return true;
}
}
}
return false;
}

Hack
Dec 29th, 2005, 09:15 AM
Post a little explanation regarding what it does and how it could be used (new folks would probably not have a clue what is going on here. :) )

Kasracer
Dec 29th, 2005, 09:58 AM
Post a little explanation regarding what it does and how it could be used (new folks would probably not have a clue what is going on here. :) )
Hopefully I did a good enough job. I'm not very good at explaining things.

Hack
Dec 29th, 2005, 11:23 AM
Hopefully I did a good enough job. I'm not very good at explaining things.It looks just fine to me. Thanks! :thumb:

wossname
Jan 13th, 2006, 08:02 AM
Eratosthenes is primarily used to generate a long list of primes and not just test primality of a single number. It would be MUCH faster just to try to divide the number by all odd integers <= sqrt(number). Also discard number if (number & 1) == 0.

PT Exorcist
Jan 26th, 2006, 09:02 AM
anyways, kasracer put a link that explained it