|
-
Dec 29th, 2005, 09:13 AM
#1
IsPrime in C#
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 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.
VB Code:
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[[b][/b]i])
{
for (Int32 j = i * 2; j < ToBeChecked+1; j += i)
numbers[j] = false;
if (numbers[i])
{
if (ToBeChecked == i)
{
return true;
}
}
}
return false;
}
Last edited by Kasracer; Dec 29th, 2005 at 09:40 AM.
-
Dec 29th, 2005, 09:15 AM
#2
Re: IsPrime in C#
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. )
-
Dec 29th, 2005, 09:58 AM
#3
Re: IsPrime in C#
 Originally Posted by Hack
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.
-
Dec 29th, 2005, 11:23 AM
#4
Re: IsPrime in C#
 Originally Posted by kasracer
Hopefully I did a good enough job. I'm not very good at explaining things.
It looks just fine to me. Thanks!
-
Jan 13th, 2006, 08:02 AM
#5
Re: IsPrime in C#
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.
I don't live here any more.
-
Jan 26th, 2006, 09:02 AM
#6
yay gay
Re: IsPrime in C#
anyways, kasracer put a link that explained it
\m/  \m/
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|