网摘 |  收藏 | 

LINQ判断素数

 

        static bool IsPrime(int n)
        {
            return Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i != 0);
        }

相关知识一:

Enumerable.Range Method

Generates a sequence of integral numbers within a specified range.

Namespace:  System.Linq
Assembly:  System.Core (in System.Core.dll)

public static IEnumerable<int> Range(
    int start,
    int count
)

Parameters

start
Type: System.Int32
The value of the first integer in the sequence.
count
Type: System.Int32
The number of sequential integers to generate.

Return Value

Type: System.Collections.Generic.IEnumerable<Int32>
An IEnumerable<Int32> in C# or IEnumerable(Of Int32) in Visual Basic that contains a range of sequential integral numbers.
ExceptionCondition
ArgumentOutOfRangeException

count is less than 0.

-or-

start + count -1 is larger than MaxValue.

参考http://www.oschina.net/code/snippet_817257_15450

 

 

posted @ 2012-11-20 11:12  xulonghua219  阅读(251)  评论(0编辑  收藏  举报