http://www.codinghelmet.com/  

Wear a helmet. Even when coding.

hints > linq-prime-test

LINQ Expression to Test If a Number is Prime
by Zoran Horvat @zoranh75

Suppose that we want to test whether a given integer number greater than one is prime. We can accomplish that with a simple for loop:

int number = 719;

bool isPrime = true;
for (int divisor = 2; divisor <= Math.Sqrt(number); divisor++)
    if (number % divisor == 0)
    {
        isPrime = false;
        break;
    }

Console.WriteLine("Number {0} is {1}prime.", number, isPrime ? "" : "not ");

This loop works fine and it really detects that 719 is a prime number.

The same effect can be accomplished with LINQ. Here is the LINQ expression which returns exactly the same result as the previous loop:

bool isPrime =
    Enumerable.Range(2, (int)Math.Sqrt(number) - 1)
    .All(divisor => number % divisor != 0);

This simple expression iterates through numbers up to the square root of the tested value and tries to divide the value with each of the numbers in the range. Loop exits when the first divisor is detected and subsequent divisions are not performed. This guarantees optimal execution of the expression.

See also:

Published: Dec 14, 2014

ZORAN HORVAT

Zoran is software architect dedicated to clean design and CTO in a growing software company. Since 2014 Zoran is an author at Pluralsight where he is preparing a series of courses on design patterns, writing unit and integration tests and applying methods to improve code design and long-term maintainability.

Follow him on Twitter @zoranh75 to receive updates and links to new articles.

Watch Zoran's video courses at pluralsight.com (requires registration):

Tactical Design Patterns in .NET: Managing Responsibilities

Applying a design pattern to a real-world problem is not as straightforward as literature implicitly tells us. It is a more engaged process. This course gives an insight into tactical decisions we need to make when applying design patterns that have to do with separating and implementing class responsibilities. More...

Tactical Design Patterns in .NET: Control Flow

Improve your skills in writing simpler and safer code by applying coding practices and design patterns that are affecting control flow. More...

Improving Testability Through Design

This course tackles the issues of designing a complex application so that it can be covered with high quality tests. More...

Share this article

webmasters