- #1
user366312
Gold Member
- 89
- 3
- Homework Statement
- I need to implement Fermat's primality tester in Python. I don't know Python very well. So, I am implementing it in C#. If I succeed, I will convet it to Python.
- Relevant Equations
- https://en.wikipedia.org/wiki/Fermat_primality_test
Fermat's Primality Tester:
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();
}
}
Output:
An unhandled exception of type 'System.OverflowException' occurred in mscorlib.dll
Additional information: Arithmetic operation resulted in an overflow.
I have two questions:
- Is this implementation correct? If not, why?
- How to get rid of this overflow exception?