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.
#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
- Hello, World · The classic first C program.
- Sum of two numbers · Read two numbers with scanf and print their sum.
- Pointers: swap two numbers · Pass addresses to a function so it can change the caller’s variables.
- Sort an array (bubble sort) · Sort numbers by swapping neighbours until nothing moves.
- Structs and malloc · Build a small linked list on the heap, print it and free it.