【问题标题】:Why is this Fermat primality tester giving me an exception? [duplicate]为什么这个费马素数测试仪给了我一个例外? [复制]
【发布时间】:2020-03-16 03:00:35
【问题描述】:

为什么这个费马素数测试仪给我一个例外?

class PrimeTest
{
    public static bool IsPrime(long n, int iteration = 5)
    {
        Random r = new Random();
        long a = 0;
        long aPow = 0;

        for (int i = 0; i < iteration; i++)
        {
            a = r.Next(1, Convert.ToInt32(n - 1));

            double x = Convert.ToDouble(a);
            double y = Convert.ToDouble(n - 1);
            double p = Math.Pow(x, y);

            aPow = Convert.ToInt64(p);//<==== this line is giving an exception.

            if (1 % n == aPow % n)
            {
                return true;
            }
        }

        return false;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("{0}", PrimeTest.IsPrime(33));
        Console.ReadLine();
    }
}

输出

An unhandled exception of type 'System.OverflowException' occurred in mscorlib.dll

Additional information: Arithmetic operation resulted in an overflow.

【问题讨论】:

  • 似乎异常很清楚。 p 的值不在long 允许的范围内。请参阅标记重复,这几乎是相同的问题,只是针对 int 而不是 long

标签: c# primes


【解决方案1】:

您的a 是一个随机数 [1~n-1],a^(n-1) 很容易大于Int64.Max 例如,a=10 和 10^32 大于 Int64.Max。

        Random r = new Random();
        long a = 0;
        long aPow = 0;

        for( int i = 0; i < iteration; i++ ) {
            a = r.Next( 1, Convert.ToInt32( n - 1 ) );

            // p is 1E32; if a==10
            double p = Math.Pow( Convert.ToDouble( a ), Convert.ToDouble( n - 1 ) );

            // Int64 is 9223372036854775807, which is less than 1E32
            aPow = Convert.ToInt64( p ); //giving exception

            if( 1 % n == aPow % n ) {
                return true;
            }
        }

        return false;

【讨论】:

    【解决方案2】:

    运行你的程序,我得到了:

    3.4336838202925124E+30,或3433683820292512400000000000000

    Int64long 的最大值是 9223372036854775807

    很容易看出为什么您会收到Overflow Exception。如果您查看消息,您会看到更多详细信息:

    Arithmetic operation resulted in an overflow.

    这个数字太大了,无法放入 long 值。

    【讨论】:

    • 我不知道这个算法。但你的问题是Why is code this giving me this exception?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2018-07-29
    • 2020-09-25
    相关资源
    最近更新 更多