问题
I got this code that checks if a number is a prime:
public static bool isPrime(int num)
{
if (num == 1) return false;
if (num == 2) return true;
int newnum = Math.Floor(Math.Sqrt(num));
for (int i = 2; i <= newnum; i++)
if (num % i == 0) return false;
return true;
}
Is there any better and faster way to check if a number is a prime?
回答1:
Yes there is. For one, you could check for 2 separately and then loop through only odd numbers. That would cut the search loop in half. There could be more elaborate things to do but basically that should answer your question.
UPDATED WITH CODE:
public static bool IsPrime(int number)
{
if (number < 2) return false;
if (number % 2 == 0) return (number == 2);
int root = (int)Math.Sqrt((double)number);
for (int i = 3; i <= root; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
There are many duplicate discussions on SO and plenty of links about various primality search methods. However, since the OP here has a method to check a signed 32-bit integer, and not something much larger like an unsigned 64-bit integer, then a quick check shows the truncated square root of int.MaxValue to be 46340. Since we are looping through only odd numbers that would result in a maximum loop of 23170 iterations, which in my opinion is quite fast as long as we are limiting the discussion to Int32. If the question revolved around UInt64, then other methods should maybe be investigated regarding faster.
The code above takes care of any int value, not just the special case of 1. Perhaps you have a NumericUpDown control that limits the inputs but I don't know that from just the function shown. One could argue that it would be more proper to throw an exception if the input number is < 2, but I skipped that 'feature' here.
All even numbers are checked before the main loop, not just 2 (a common mistake).
And while this could be homework (in July!!!), there are tons of links throughout the Internet that would have similar code so I am not doing someone's homework for them. Since my code was added days after the original post, the OP has had time to research and learn since then.
来源:https://stackoverflow.com/questions/17579091/faster-way-to-check-if-a-number-is-a-prime