C# 为什么这个费马素性测试仪给了我一个例外?
为什么这个费马素性测试仪给了我一个例外C# 为什么这个费马素性测试仪给了我一个例外?,c#,primes,C#,Primes,为什么这个费马素性测试仪给了我一个例外 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
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();
}
}
运行您的程序,我得到:
3.4336838202925124E+30
,或3433683820292512400000000
而Int64
或long
的最大值为9223372036854775807
很容易理解为什么会出现溢出异常
。如果您查看该消息,您将看到更多详细信息:
算术运算导致溢出。
该数字太大,无法放入
long
值中。您的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;
Random r=new Random();
长a=0;
长aPow=0;
for(int i=0;i
例外情况似乎很明显。值p
不在long
允许的范围内。请参阅标记的复制,它几乎是相同的问题,只针对int
而不是long
。我不知道这个算法。但是你的问题是为什么这段代码会给我这个例外?
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;