How to check quickly if a number is prime in C?
- User
How to check quickly if a number is prime in C?
- Assistant
Fundamentally there is no "quick" solution, the required time depends on the size of the number. Many primality test algorithms have been developed but for small numbers the below simple algorithm should be sufficient. It does some fast check and if those don't reach a conclusion, try every possibly suitable division:
bool IsPrime(int n) { if (n == 2 || n == 3) return true;
if (n <= 1 || n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true;}
This is correct but not quick for large numbers. For large numbers you could look for faster methods. A common way to speed up these algorithms is to pre-compute and store a list of all primes up to a certain bound. This reduced the number of division tests since dividing by only prime numbers is sufficient for the test.
- User
Can you make unit tests for that function?
- Assistant
Yes, here are some unit tests for the IsPrime function:
#include
void TestIsPrime() { assert(IsPrime(2) == true); assert(IsPrime(3) == true); assert(IsPrime(4) == false); assert(IsPrime(5) == true); assert(IsPrime(6) == false); assert(IsPrime(7) == true); assert(IsPrime(8) == false); assert(IsPrime(9) == false); assert(IsPrime(10) == false); assert(IsPrime(11) == true); }
int main() { TestIsPrime(); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)