Last active
October 17, 2024 09:13
-
-
Save marsgpl/666b4710b160cfed6b8cd8a3688fbca5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// n must have exactly 2 distinct divisors to be prime | |
int is_prime(int n) { | |
if (n < 0) { | |
n = -n; | |
} | |
if (n <= 100) { // first 25 primes (add more?) | |
switch (n) { | |
case 2: case 3: case 5: case 7: case 11: case 13: case 17: | |
case 19: case 23: case 29: case 31: case 37: case 41: case 43: | |
case 47: case 53: case 59: case 61: case 67: case 71: case 73: | |
case 79: case 83: case 89: case 97: | |
return 1; // prime | |
default: | |
return 0; // not prime | |
} | |
} | |
for (int i = 2; i < n; ++i) { // exclude 1 and n | |
if (n % i == 0) { | |
return 0; // not prime: divisible by i | |
} | |
} | |
return 1; // prime | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment