logo

30-second algorithm to check if a number is prime

#include <stdio.h> #include <stdlib.h> #include <string.h> int isPrime(int x) { if (x < 2 || x % 2 == 0 && x != 2) { return 0; } int d; int s = floor(sqrt(x)); for (d = 3; d <= s; d += 2) { if (x % d == 0) { return 0; } } return 1; } int main(int argc, char* argv[]) { if (isPrime(17) == 1) { printf("Is prime\n"); } else { printf("Is not prime\n"); } return 0; }
Course thumb

The C programming language made simple