RUN

Check a prime number in C

Test whether a number is prime by trying divisors up to its square root. Press Run to try it, then change the code and run it again.

main.c

#include <stdio.h>
#include <stdbool.h>

bool is_prime(int n) {
    if (n < 2) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

int main(void) {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("%d is %s\n", n, is_prime(n) ? "prime" : "not prime");
    return 0;
}
Output

Press Run to see the output.

More C examples

Open the full C online compiler →