Compare the methods of determining prime numbers with code and concept.
i.Naive method
ii.square root method
iii.Seive of Eratosthenes
bool isPrime(int n)
{
if (n <= 1)
return false;
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
A more intuitive explanation of the same thing. For the same reasons.
The square root of 100 is 10. Let's say a x b = 100, for various pairs of a and b.
If a == b, then they are equal, and are the square root of 100, exactly. Which is 10.
If one of them is less than 10, the other has to be greater. For example, 5 x 20 == 100. One is greater than 10, the other is less than 10.
The conclusion of all this:
1) square root method is more optimized than naive method;
2)Seive of Eratosthenes is more optimized than square root method
Comments
Leave a comment