Prime Number Calculation in C#

10 Nov 2013

C#, Maths


A simple method for prime calculation involves:

Example 1: Is 3 a prime?

Example 2: Is 27 a prime?

Example 3: Is 392 a prime?

The code is quite simple, and is presented here written as an extension.



#region Using References 

using System; 

using Maths = System.Math; 

#endregion 

public static class Extensions 
{ 
    #region Methods 

    public static bool IsPrime(this long Value) 
    { 
        bool bIsPrime = true; 

        // Assume that the integer supplied is actually a prime, then test for
        // statements that make this condition false
        long lSquareRoot = (long)(Maths.Sqrt(Value)); 

        for (long l = 2; l <= lSquareRoot; l++) 
        { 
            //  If the result of this calculation is greater than zero, then we will consider the integer to be prime
            //  If we encounter one zero result in this loop, we will consider the integer to NOT be prime

            bIsPrime = ((long)(Value % l) > 0); 

            if (bIsPrime == false) 
            { 
                // Break out of the loop
                break; 
            } 
        } 

        return bIsPrime; 
    } 

    #endregion 
} 


 

Copyright © 2024 carlbelle.com