【发布时间】: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。