Skip to content
Devtoolry

Numbers · beginner

C Program to Check Prime Number

Check whether a number is prime in C by testing divisors up to its square root with i * i <= n in a reusable function, avoiding the bugs that make 9 look prime.

A prime number is a whole number greater than 1 that is divisible only by 1 and itself. To test n, try every divisor from 2 upwards; one exact division proves n is not prime.

Divisors only need checking up to √n, because a larger factor always pairs with a smaller one. Writing the loop condition as i * i <= n avoids calling sqrt() from math.h and its floating-point rounding.

The program

C
#include <stdbool.h>
#include <stdio.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 tests[] = {1, 2, 9, 29, 97};
    for (int k = 0; k < 5; k++) {
        printf("%d is %s\n", tests[k], is_prime(tests[k]) ? "prime" : "not prime");
    }
    return 0;
}
Output
1 is not prime
2 is prime
9 is not prime
29 is prime
97 is prime

How it works

  1. Numbers below 2 are not prime by definition, so the function returns false at once.
  2. The loop tries i = 2, 3, 4, … while i * i <= n, which is the same as i <= √n.
  3. If n % i == 0, i divides n exactly, so n is not prime and the function returns immediately.
  4. If no divisor is found, the function returns true. For 2 and 3 the loop body never runs.

Another way: Reading the number with scanf

The same check for a number typed by the user, with the return value of scanf checked. Skipping even numbers after 2 halves the work.

C
#include <stdio.h>

int main(void) {
    int n;
    if (scanf("%d", &n) != 1) {
        printf("Not a number\n");
        return 1;
    }
    int prime = n == 2 || (n > 2 && n % 2 != 0);
    for (int i = 3; prime && i * i <= n; i += 2) {
        if (n % i == 0)
            prime = 0;
    }
    printf("%d is %s\n", n, prime ? "prime" : "not prime");
    return 0;
}
Input (stdin)
91
Output
91 is not prime

Common mistakes

  • Missing the n < 2 check, so 0 and 1 come out as prime.
  • Writing i * i < n instead of <=, which misses perfect squares: 9, 25 and 49 then look prime.
  • Using i <= sqrt(n) without linking the math library (-lm) or with rounding errors for large n.
  • For n near INT_MAX, i * i can overflow int. Use long long for i, or the condition i <= n / i.

Try it yourself

  • Print the smallest divisor of a non-prime number.
  • Count the primes below 100,000 (there are 9,592).

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.