ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IsPrime

Returns true when a integer is a prime.

Source

static class Extensions { 

    public static bool IsPrime(this int number) { 
        if ((number % 2) == 0) { 
            return number == 2; 
        } 
        int sqrt = (int)Math.Sqrt(number); 
        for (int t = 3; t <= sqrt; t = t + 2) { 
            if (number % t == 0) { 
                return false; 
            } 
        } 
        return number != 1; 
    } 
}

Example

bool b = 7.IsPrime(); // true

Author: Fons Sonnemans

Submitted on: 21 aug. 2007

Language: C#

Type: System.Int32

Views: 11681