c# - 为什么这个费马素数测试仪给了我一个例外?
问题描述
为什么这个费马素数测试仪给了我一个例外?
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.
解决方案
你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;
推荐阅读
- ios - CoreData 可以工作,但在控制台中又返回了一个 nil 对象?
- dart - StreamBuilder 会在无状态小部件中自动关闭流吗?
- python - 如何在循环中传递csv的标题
- java - 由于字符串中的斜线,字符串到 JSONArray 给出异常
- search - SearchDelegate 不调用 buildResults 方法
- java - 使用 Alfresco 中的 AuthorityService 从组中获取用户作为分页结果
- equality - 组件上的对等式
- javascript - 当我的数据为真时如何返回
- python - 如何说服 DateTime 对象(使用 pytz 时区初始化)让我获得 pytz 识别的时区代码?(Python)
- php - Cakephp 3.6.14:动作拒绝后重定向