如何检查数字是否为梅森素数?

时间:2016-07-24 16:22:42

标签: c# primes

检查Int32 n是否为梅森素数的有效方法是什么? 这是我的尝试:

显然,对于某些梅森素数的数字,此代码返回true,例如31但不适用于127等其他人。 有人能告诉我我的代码有什么问题吗?

/// <summary>
/// Checks if a nubmer is a mersenne prime
/// </summary>
/// <param name="candidate"></param>
/// <returns></returns>
public static bool IsMersennePrime(uint n)
{    
    var x = Math.Pow(2, n) - 1;
    return IsPrime((uint)x);
}

/// <summary>
/// Checks if a nubmer is a prime
/// </summary>
/// <param name="candidate"></param>
/// <returns>true if number is a prime false if its not a prime</returns>
private static bool IsPrime(uint candidate)
{
    //
    // Test whether the parameter is a prime number.
    //
    if ((candidate & 1) == 0)
    {
        if (candidate == 2)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    int num = (int)Math.Sqrt((double)candidate);
    for (int i = 3; i <= num; i += 2)
    {
        if ((candidate % i) == 0)
        {
            return false;
        }
    }
    return true;
}

1 个答案:

答案 0 :(得分:2)

因为您只想要符合uint的Mersenne素数,最好的方法是检查实际值。详细了解A000043A000668

private static int[] A000043 = new int[] { 2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657 };
private static int[] A000668 = new int[] { 3, 7, 31, 127, 8191, 131071, 524287, 2147483647 };

public static bool IsInA000668(int value) => A000668.Contains(value);
public static bool IsInA000043(int value) => A000043.Contains(value);