How to check quickly if a number is prime in C?
- User
How to check quickly if a number is prime in C?
- Assistant
Here is a simple algorithm for checking if a number is prime in C. This implementation uses two optimizations to determine if a number is prime. First, if the number is divisible by 2 or 3, it is not considered prime. Second, the fact that all primes can be expressed as 6k ± 1 is utilized, allowing for faster processing by checking multiples of 6:
#include <math.h> #include <stdbool.h>
bool is_prime(int num) { if (num <= 1) return false; if (num <= 3) return true; if (num % 2 == 0 || num % 3 == 0) return false;
int i; for (i = 5; i <= sqrt(num); i += 6) { if (num % i == 0 || num % (i + 2) == 0) return false; } return true;}
- User
This is still running slow for me with larger numbers. Any other optimizations I can add to go a bit faster?
- Assistant
Yes, there are a few additional optimizations you can add to further improve the performance of this algorithm:
Check for divisibility by smaller primes: Before checking for divisibility by 6k ± 1, you can check for divisibility by smaller primes, such as 2, 3, 5, 7, 11, etc. This will save time as the smaller primes will divide many numbers before 6k ± 1 has a chance. Check only odd numbers: Since all even numbers are not prime, you can skip checking them and only check odd numbers. This will reduce the number of checks required by half. Use an optimized method for finding the square root: Instead of using the sqrt function from the math.h library, you can use an optimized method for finding the square root, such as the Newton-Raphson method or the Binary Search method. These methods are faster than the standard sqrt function and can improve the performance of the algorithm.Here's an updated implementation incorporating these optimizations:
#include <stdbool.h>
bool is_prime(int num) { if (num <= 1) return false; if (num <= 3) return true; if (num % 2 == 0 || num % 3 == 0) return false; if (num % 5 == 0 || num % 7 == 0 || num % 11 == 0) return false;
int i; for (i = 13; i * i <= num; i += 2) { if (num % i == 0) return false; } return true;
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)