Q: Finding whether or not a number is prime?
Sol: There are several ways to solve this problem. Lets look into some of the more trivial approaches as usual and try to improve on these as we move along.
By Definition, a prime number is a positive integer having exactly one positive divisor other than 1. Therefore the straightforward way to do this will be to check divisibility of the given number starting from 2 to the given number.
There are some easy ways to improve upon this basic approach.
void GetPrimes(int n)
{
// Start from 3
int j=3;
// There is already one prime (2), so set count=1
int count = 1;
while(count < n)
{
int check = (int)sqrt(double(j));
bool fPrimeFound=true;
for(int i=2; i<=check; i++)
{
if(j%i==0)
{
fPrimeFound=false;
break;
}
}
if(fPrimeFound)
{
//printf("%d ", j);
count++;
}
j++;
}
}
Comments
why not to just check if the
why not to just check if the number is not even and not dividable by 3 or 5
ex :
//prime numbers should not be divisible by 2 or 3 or 5
for(int iCurrentNumber = ilow ; iCurrentNumber <= ihigh ; iCurrentNumber++)
{
//check the number
if (iCurrentNumber % 2 != 0 && iCurrentNumber % 3 != 0 && iCurrentNumber % 5 != 0)
{
cout<<iCurrentNumber<<endl;
}
//special case for 3 and 5
if (iCurrentNumber == 3 | iCurrentNumber == 5)
{
cout<<iCurrentNumber<<endl;
}
}
[...] Q: Finding the first N
[...] Q: Finding the first N primes. In the last post, we looked into some trivial approaches. How can we make this faster? [...]
[...] Q: Finding the first N
[...] Q: Finding the first N primes. In the last post, we looked into some trivial approaches. How can we make this faster? [...]
[...] In the last post we
[...] In the last post we looked into making some improvements over Trivial Approaches [...]
[...] Technical Interview
[...] Technical Interview Questions The largest pool of technical questions with answers, explantions, code and detailed analysis « Prime Numbers: Finding the first N Primes Part 1 Trivial Approaches [...]