// This function is called for all k trials. // It returns false if n is composite and // returns false if n is probably prime. // d is an odd number such that d*2<sup>r</sup> // = n-1 for some r >= 1 private bool MillerTest(int d, int n) { // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + (int)(rng.Next() % (n - 4)); // Compute a^d % n int x = ComputationUtils.Power(a, d, n); if (x == 1 || x == n - 1) { return(true); } // Keep squaring x while one of the // following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) { return(false); } if (x == n - 1) { return(true); } } return(false); }
public bool IsPrime(int n) { // If it is composite and satisfy Fermat criterion if (a > 1 && IsComposite(n) && ComputationUtils.Power(a, n - 1, n) == 1) { return(true); } // Else return 0 return(false); }