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?
The simplest primality test is trial division: given an input number, n, check whether it is evenly divisible by any prime number between 2 and √n (i.e. that the division leaves no remainder). If so, then n is composite. Otherwise, it is prime.
The number 2 is divisible only by 1 and the number itself. For a number to be classified as a prime number, it should have exactly two factors. Since 2 has exactly two factors, i.e. 1 and 2, it is a prime number.
Function isPrime2 is faster in returning True for prime numbers. But if a number is big and it is not prime, it takes too long to return a value. First function works better with that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With