Sha256: e0db5fbdc5264510427ac1032c2eabd97def26d40085037e7cd8fa7cdf5da55a

Contents?: true

Size: 804 Bytes

Versions: 125

Compression:

Stored size: 804 Bytes

Contents

using System;
using System.Collections.Generic;
using System.Linq;

public static class NthPrime
{
    public static int Nth(int nth)
    {
        return Primes().Skip(nth - 1).First();
    }

    private static IEnumerable<int> Primes()
    {
        yield return 2;
        yield return 3;

        foreach (var prime in PossiblePrimes().Where(IsPrime))
        {
            yield return prime;
        }
    }

    private static IEnumerable<int> PossiblePrimes()
    {
        var n = 6;

        while (true)
        {
            yield return n - 1;
            yield return n + 1;

            n += 6;
        }
    }

    private static bool IsPrime(int n)
    {
        var r = (int)Math.Floor(Math.Sqrt(n));

        return r < 5 || Enumerable.Range(5, r - 4).All(x => n % x != 0);
    }
}

Version data entries

125 entries across 125 versions & 1 rubygems

Version Path
trackler-2.0.8.24 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.23 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.22 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.21 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.20 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.19 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.18 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.17 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.16 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.15 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.14 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.13 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.12 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.11 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.10 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.9 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.8 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.7 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.6 tracks/csharp/exercises/nth-prime/Example.cs
trackler-2.0.8.5 tracks/csharp/exercises/nth-prime/Example.cs