Ad space (banner)
๐Ÿ”งC Lessons
Lesson 60 / 68

Checking Whether a Number Is Prime

This lesson covers checking whether a number is prime in C, so you understand a basic math algorithm using a loop. It's for anyone searching "C prime check implementation."

Whether a number is prime (divisible only by 1 and itself) can be determined by checking whether it's divisible by any number from 2 up to its square root. If none of them divide it evenly, it's prime.

The example loops over the range for (int i = 2; i * i <= n; i++), deciding the number isn't prime the moment it finds an i where n % i == 0. Notice using the stdbool.h header to work with a bool return value.

A common early mistake is not knowing older C standards have no bool type. Including stdbool.h lets you use true/false, available from C99 onward.

It's an important mathematical property that underlies cryptography too, and there's also a more advanced technique, the Sieve of Eratosthenes, for efficiently finding many primes at once.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)