Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Function] Check For Prime - C# Source
#1
I don't see too much C# stuff here, even though all I mainly do is VB.net and once in a while some C++. But here's a function I created in C# to check whether a number is prime or not, given a returned boolean value.

I'll post the usage as well so you can try it out. To see, you can change around the variable of x which is just a type Int32.

Code:
private void button1_Click(object sender, EventArgs e)
{
    int x = 21;
    MessageBox.Show(x + (IsPrime(x) ? " is a prime" : " is not a prime"));
}

private bool IsPrime(int input)
{
    if (input == 2)
    {
        return true;
    } else if (input == 1 || input % 2 == 0) {
        return false;
    }

    for (int n = 3; n < input / 2; n += 2)
    {
        if (input % n == 0 && n != input) { return false; }
    }
    return true;
}

Nice efficient way of checking for primes Smile I think I posted a VB.net version of this as well. But basically the way it works is it does a few firsthand checks; the only prime number divisible by 2 is 2. 0 and 1 are special numbers, NOT prime numbers.

If we know a prime number other than 2 cannot be divisible evenly by 2 then we can skip all even numbers from 3 and up. So in our loop, we can utilize n to check each odd number from 3 forward by adding 2 each time.

Lastly, we only need to go just before the halfway point, as any further and we'll basically be checking the multiples in reverse.

Example:
3 * 7

If we know 21 is divisible by 3, which is 7, then we don't need to continue our loop to 7 since we know it's divisible by a factor of 3... Bad example, as 7 is not the halfway point for 21, but you can see the strategy in not having to go anywhere past the halfway point as we'll start running into the opposite multiples by that point undoubtedly.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Source ] Hemp Tycoon App [/Source] VB.net KoBE 8 9,748 03-05-2012, 10:30 PM
Last Post: SomeWhiteGuy?
  [Source]Sql Database Project [Source] Digital-Punk 0 1,438 10-16-2011, 07:01 AM
Last Post: Digital-Punk
  [Source]Batch to Exe converter[Source] Digital-Punk 6 2,982 10-15-2011, 03:00 AM
Last Post: Digital-Punk
  [Source]File Assembly changer Vb.Net[Source] Digital-Punk 0 3,102 10-13-2011, 06:35 PM
Last Post: Digital-Punk
  [New\Source\Release] Binary Code <> English Converter [New\Source\Release] Resistance 16 8,040 05-15-2011, 05:42 AM
Last Post: Blixx

Forum Jump:


Users browsing this thread: 1 Guest(s)