Sunday, July 12, 2009

C programming?

Write functions to:





int isprime(int); /* Returns a true value if a is a prime number */

C programming?
int isprime(int a) {


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


if (a%i == 0) return 0;


}


return 1;


}





The only difference between mine and Milo's is "i %26lt;= a/2" instead of "i %26lt; a/2", and the only place that would make a difference is for a=4 (Milo's would wrongly return 1 (prime) when it should return 0 (not prime)).





JCPENNY's "correction" is fundamentally incorrect. 1 means "true" means "is prime" as in Milo's answer.





x2000 is of course right in his optimization. Imagining this question being asked by a beginner, I was trying to avoid bit twiddling. However, since the subject has been breached "if(!(a%26amp;1)) return 0;" might be marginally faster on some systems.





Another optimization, particularly useful for large values of "a", would be to stop at "i %26lt;= ((int) sqrt(a))" rather than "i %26lt;= a/2". Having said that, for reasons I don't want to get into here, some square root calculations for some perfect squares on some machines when truncated to integer will be one less than the correct number. If it so happened that our "a" was one of these numbers and further that "a" was the square of a *prime* number, then the function would incorrectly judge "a" to be prime. So to be on the safe side I would use "i %26lt;= ((int) sqrt(a+1))" instead.





Any marginally proficient optimizer should calculate the square root expression once, outside the loop. But, if you want to be ABSOLUTELY SURE, then set up your own variable before the loop and use it to test against "i".





--------------


EDIT: It appears x2000 deleted his answer (which is a shame; it was actually pretty good). he basically said that you could just check once for all even numbers using a binary "bit twiddling" trick:





if((a%26amp;1) == 0) return 0;





and then avoid even numbers in the loop:





for(int i = 3; i %26lt;= a/2; i += 2)





My comments above for "x2000" were directed at his answer.
Reply:int isprime(int a) {


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


if (a%i == 0)


return 0;


}


return 1;


}





I didn't test it, but it should work.
Reply:I agree with the design of the previous answer, but the coding is a bit off. The return statements would give you the wrong result. Here's what I would to:





int IsPrime(int a)


{


for(int i = 2; i%26lt;a/2; i++)


{


if(a % i == 0)


{ return 1;}


}


return 0;


}





In this case, if the function returns 0 then the number is a prime. If 1 is returned then that means it was evenly divisible by a number (i) and therefore is not prime.


No comments:

Post a Comment