Monday, July 27, 2009

Can u give me the source code of prime numbers in dev c++??

plss shorten the source code

Can u give me the source code of prime numbers in dev c++??
A function that returns true if a number is prime:





bool isPrime(int p){


  if ( p%26lt;=1 ) return false;


  if ( p == 2 ) return true;


  if ( p %26gt; 2 ){


   for(int i = 2; i %26lt; p; ++i){


    if (p%i == 0) return false;


   }


   return true;


  }


}





To list all prime numbers from a to b:





for(int i = a; i %26lt;= b; ++i){


  if (isPrime(i)) cout %26lt;%26lt; i;


}
Reply:Your question is not very clear, but...here is a basic function to get you started.





#include %26lt;cmath%26gt;





bool IsPrime(int num)


{


// no number can divide into 0


if(num == 0)


return true;





// make sure it's not negative


num = abs(num);





for(int i = 2; i %26lt;= sqrt(num); i++)


if(num % i == 0)


return false;





return true;


}
Reply:#include %26lt;stdio.h%26gt;








int main(void) {


int n,


lcv,


flag; /* flag initially is 1 and becomes 0 if we determine that n


is not a prime */





printf("Enter value of N %26gt; ");


scanf("%d", %26amp;n);


for (lcv=2, flag=1; lcv %26lt;= (n / 2); lcv++) {


if ((n % lcv) == 0) {


if (flag)


printf("The non-trivial factors of %d are: \n", n);


flag = 0;


printf("\t%d\n", lcv);


}


}


if (flag)


printf("%d is prime\n", n);


}


No comments:

Post a Comment