I have written a code which checks whether a integer is prime or not,whenever i am calling that function the command line just hangs. I am using MingW in Windows 7
#include<iostream>
#include<math.h>
using namespace std;
bool checkPrime(int n);
int main()
{
int t,tempstart;
cout<<checkPrime(6);
return 0;
}
bool checkPrime(int n)
{
bool check=true;
for (int i = 0; i <(int) sqrt(n) ; i++)
{
if(n%i==0)
{
check=false;
cout<<"asas";
break;
}
}
return check;
}
it should not hang-up at least not for n=6
1.try this
instead of:
if(n%i==0)
write:
if((n%i)==0)
some compilers do a mess with multi operation conditions so bracketing usually helps
2.as mentioned i should go from 2
3.have you try to debug it ?
Tips for speeding it up a little (just few thousand times for bigger n)
1.i=2,3,5,7,9,11,13,...
and the rest:
for (nn=sqrt(n),i=3;i<=nn;i+=2) ...
2.instead of sqrt(n) use number with the half of bits
3.do not compute sqrt inside for (some compilers do not pre-compute)
4.use sieve of Aristoteles
for example array
BYTE sieve[4106301>>1]; //only odd numbers are important so the size is half and each bit hold one sieve value so the size is really 4106301*8 which is divided by:
can hold sieves for dividers:
5.divide by primes
and the use
for (nn=sqrt(n),i=last prime+2;i<=nn;i++) ...
also you can remember all primes computed on runtime in some list and use them
6.you can combine all above all together
7.there are many other ways to improve performance of is_prime(n) ?
According to the operator precedence in C++ % has more priority than == so you should be using
if((n%i)==0)
good luck!
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