Results 1 to 6 of 6

Thread: IsPrime in C#

Threaded View

  1. #1

    Thread Starter
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985

    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:
    1. public static bool IsPrime(Int32 ToBeChecked)
    2. {
    3.     System.Collections.BitArray numbers = new System.Collections.BitArray(ToBeChecked+1, true);
    4.     for (Int32 i = 2; i < ToBeChecked+1; i++)
    5.         if (numbers[[b][/b]i])
    6.         {
    7.             for (Int32 j = i * 2; j < ToBeChecked+1; j += i)
    8.                 numbers[j] = false;
    9.             if (numbers[i])
    10.             {
    11.                 if (ToBeChecked == i)
    12.                 {
    13.                     return true;
    14.                 }
    15.             }
    16.         }
    17.     return false;
    18. }
    Last edited by Kasracer; Dec 29th, 2005 at 09:40 AM.
    KrisSiegel.com - My Personal Website with my blog and portfolio
    Don't Forget to Rate Posts!

    Free Icons: FamFamFam, VBCorner, VBAccelerator
    Useful Links: System.Security.SecureString Managed DPAPI Overview Part 1 Managed DPAPI Overview Part 2 MSDN, MSDN2, Comparing the Timer Classes

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width