Determining Primality in C
Your request to determine if a given integer is prime in C brings up an intriguing programming challenge. Let's break down the steps to achieve this:
In C#, your code implements this algorithm as follows:
static bool IsPrime(int number) { for (int i = 2; i < number; i++) { if (number % i == 0 && i != number) return false; } return true; }
Adapting to C:
To translate this code to C, we need to make some minor changes:
The following modified C code performs the same task:
int IsPrime(unsigned int number) { if (number <= 1) return 0; // Zero and one are not prime unsigned int i; for (i = 2; i * i <= number; i++) { if (number % i == 0) return 0; } return 1; }
This code checks for divisibility up to the square root of the integer to optimize performance and handles non-prime cases such as zero and one.
The above is the detailed content of How Can I Determine if an Integer is Prime in C?. For more information, please follow other related articles on the PHP Chinese website!