C Programming – Check Prime

An example of using boolean data type in C Programming, with stdbool.h included

bool IsPrime (int n)
int i, limit;
if (n <= 1) return (false); //Special case for 1
if (n == 2) return (true); //Special case for 2
if (n%2 == 0) return (false); //Even number (except 2) can never be prime number

limit = sqrt(n) + 1; //Redundant to test for other numbers greater than sqrt(target)
for (i = 3; i <= limit; i+=2)
 if (n % i == 0) return (false);

According to “The Art and Science of C", this function is said to be very efficient.



WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )


您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s