Home - ELIASdigital.com

Prime Number Calculation in C# - 10 Nov 2013 at 20:09

Articles about Prime Number Calculation in C#

C#, Maths

Prime Number Calculation in C#

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 © 2018 ELIASdigital.com