How to check if a number is prime in C?

#include <stdio.h>

int isPrime(int n) {
    if (n < 2) return 0;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return 0;
    }
    return 1;
}

int main(void) {
    printf("%d\n", isPrime(29));
    printf("%d\n", isPrime(30));
    return 0;
}

Output:

Output of the above program is

1
0

It is enough to check divisors up to the square root of the number, so the loop is fast.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.