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

How to check if number is a Mersenne prime?

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

显然此代码 returns 对于某些梅森素数的数字是正确的,例如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;
}

由于您只需要符合 uint 的梅森素数,因此最好的方法是检查实际值。详细了解 A000043 and A000668

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);