VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-to-check-whether-a-number-is-prime-or-not/

⇱ Prime Number Program in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Prime Number Program in C

Last Updated : 11 Jul, 2025

A prime number is a natural number greater than 1 and is completely divisible only by 1 and itself. In this article, we will learn how to check whether the given number is a prime number or not in C.

Examples:

Input: n = 29
Output: 29 is Prime
Explanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime number.

Input: n = 15
Output: 15 is NOT prime
Explanation: 15 has divisors other than 1 and 15 (i.e., 3 and 5). Hence, it is not a prime number.

We can check whether a number is prime using various approaches:

Brute Force Method - O(n) Time

We can check whether the number is prime or not by iterating in the range from 1 to n using loops. We will count the number of divisors. If there are more than 2 divisor (including 1 and n) then the given number n is not prime, else n is prime. This method is known as trial division method.

Example:


Output
29 is prime

The time complexity of the above program is O(n) because we iterate from 1 to n.

Optimized Approach - O(√n) Time

To optimize the above approach, we use a mathematical property which states that,

The smallest factor of a number greater than one cannot be greater than the square root of that number.

Using this, we can reduce the numbers to be checked from N to √N making it much more efficient than above approach.

Example:


Output
29 is prime

The time complexity of the above program is O(√n) because we iterate only √n times.

We can further optimize the above approach by skipping all even numbers greater than 2. Since the only even prime number is 2, we can skip all even numbers between 3 and √n.

Example:


Output
29 is prime
Comment
Article Tags: