C # Determines whether a given large number is prime, and the target obtains the correct results at a fast rate.
When you see this problem, the first reaction this is a test of the complexity of the problem, followed by the algorithm.
Let's look at the rule of prime numbers first:
Link:http://en.wikipedia.org/wiki/prime_number
C # to find Prime code:
Copy Code code as follows:
public bool Primenumber (int n) {
int sqr = Convert.ToInt32 (MATH.SQRT (n));
for (int i = SQR i > 2; i--) {
if (n% i = = 0) {
b = false;
}
}
return b;
}
Obviously the program complexity of the above code is n
Let's optimize the code, and then look at the following code:
Copy Code code as follows:
public bool Primenumber (int n)
{
BOOL B = true;
if (n = = 1 | | n = = 2)
B = true;
Else
{
int sqr = Convert.ToInt32 (MATH.SQRT (n));
for (int i = SQR i > 2; i--)
{
if (n% i = = 0)
{
b = false;
}
}
}
return b;
}
The complexity of the program is reduced to N/2 by adding preliminary judgment.
The above two pieces of code to determine whether the number of large numbers is the correct rate is 100%, but for the problem
1. To meet the large number of judgments;
2. Demands that the correct results be obtained at the fastest speed;
is clearly not satisfied. On the internet to check the fastest algorithm to get accurate results, a recognized solution is the miller-rabin algorithm
Link:http://en.wikipedia.org/wiki/miller%e2%80%93rabin_primality_test
The basic principle of miller-rabin is to raise the speed (i.e. probability hit) by means of the random number algorithm, but at the expense of the accuracy rate.
The result of Miller-rabin to the prime number of the input is not necessarily completely accurate, but it is a basic solution to the problem.
Miller-rabin C # code:
Copy Code code as follows:
public bool Isprobableprime (BigInteger source) {
int certainty = 2;
if (Source = 2 | | source = = 3)
return true;
if (Source < 2 | | | Source% 2 = 0)
return false;
BigInteger d = source-1;
int s = 0;
while (d% 2 = 0) {
D/= 2;
s + + 1;
}
RandomNumberGenerator rng = Randomnumbergenerator.create ();
byte[] bytes = new Byte[source. Tobytearray (). Longlength];
BigInteger A;
for (int i = 0; i < certainty; i++) {
do {
Rng. GetBytes (bytes);
A = new BigInteger (bytes);
}
while (A < 2 | | | a >= source-2);
BigInteger x = Biginteger.modpow (A, d, source);
if (x = = 1 | | | x = = source-1)
Continue
for (int r = 1; r < S; r++) {
x = Biginteger.modpow (x, 2, source);
if (x = = 1)
return false;
if (x = = source-1)
Break
}
if (x!= source-1)
return false;
}
return true;
}