C Program to Check if a Number is Prime or Not

Table of Contents

C-Program-to-Check-if-a-Number-is-Prime-or-Not

In computer programming, prime numbers hold immense value. They are often the fundamental concepts of academic exercises and real-world applications, primarily in the domains of cryptography and computer security. A prime number is a natural number greater than 1, and it is only divisible by itself and 1.

Therefore, understanding how to identify prime numbers is fundamental for anyone learning to program. In this blog, we’ll explore a C program for prime numbers, specifically designed to check whether a given number is prime or not. This simple yet effective example will help beginners strengthen their grasp of loops, conditionals, and logical thinking in C programming.

Prime numbers from 1 to 100

*tutorax.com

8 Ways to Check Prime Numbers through C Program

Here are 8 ways to check C program for prime numbers

1. C Program for Prime Numbers with Simple Iterative Method

#include <stdio.h>

int main() {

    // Declare the variables

    int num, x, count = 0;

    // Input number to check

    printf(“Enter a number: “);

    scanf(“%d”, &num);

    // Check if num is less than 2

    if (num <= 1) {

        printf(“Not Prime\n”);

        return 0;  // Exit the program if num is less than or equal to 1

    }

    // Iterative loop to check divisibility

    for (x = 2; x< num; x++) {

        if (num % x == 0) {  // If divisible by x

            count++;  // Increment count

            break;    // Exit loop early if a divisor is found

        }

    }

    // Check if count is greater than 0, then it’s not prime

    if (count > 0) {

        printf(“Not Prime\n”);

    } else {

        printf(“Prime\n”);

    }

    return 0;

}

Output:

When input: 9
Enter a number: 9Prime
When input: 10
Enter a number: 10Not Prime 

Explanation

This C program for prime numbers uses a simple iteration method.

First, the code used an ‘if’ loop to check if the given input is less than 2. If it’s less than 2, which means 1 or less, the number is not prime. So the program exits.

If the number is greater than 2, then it will proceed by the ‘for’ loop, where iteration occurs. The iteration starts with 2 and (x=2) up to one less than the input. It checks the divisibility of the number. If it’s divisible by x, then the count will increase, and the number will not be prime. The program will exit the loop. 

If the count is greater than 0, then one divider will be found. So, the number is not prime. Otherwise, it will be a prime number. If the count is 0, that means no divisor is found. So, the number is prime.

2. C Program for Prime Numbers with While Loop

#include <stdio.h>

int main() {

    int n, k = 2, is Prime = 1;

    printf(“Enter a number: “);

    scanf(“%d”, &n);

    if (n <= 1) {

        isPrime = 0;

    } else {

        while (k < n) {

            if (n % k == 0) {

                isPrime = 0;

                break;

            }

            k++;

        }

    }

    if (isPrime) {

        printf(“%d is a prime number.\n”, n);

    } else {

        printf(“%d is not a prime number.\n”, n);

    }

    return 0;

}

Output:

Enter a number: 7
7 is a prime number.

Explanation

This C program checks if a number (n) is prime or not through a while loop. The loop initializes isPrime as 1 and starts iteration from 2 (k=2) up to n-1. If n is divisible by k, then isPrime becomes 0. So, the loop terminates. That means the number is not prime. 

After the while loop finishes, the program checks the value of isPrime. If its value is 1, that means the number is prime. If its value is 0, the number is not prime.

3. C Program for Prime Numbers Using Functions

#include <stdio.h> 

// function to check if 

// the num is prime or not.

int find_Prime(int num)

{

    int i, temp = 0; 

    // iterate up to num/2.

    for (i = 2; i <= num / 2; i++)

    {

        // if num has factors, 

        // update temp.

        if (num % i == 0)

        {

            temp++;

        }

    }

    return temp;

int main()

{

    int num, temp = 0; 

    printf(“Enter any number to Check for Prime: “);

    scanf(“%d”, &num);

    // function call

    temp = find_Prime(num);

    if (temp == 0 && num != 1)

    {

        printf(“\n %d is a Prime Number”, num);

    }

    else

    {

        printf(“\n %d is Not a Prime Number”, num);

    }

    return 0;

}

Output:

Enter any number to Check for Prime: 17
17 is a Prime Number 
Enter any number to Check for Prime: 14
17 is Not a Prime Number

Explanation

It’s a use case to find prime numbers in C programming using a function. Here, find_Prime is the function that iterates from 2 to half of the input. If a number divides the input without any remainder, the temp will be incremented. If temp remains 0, then the number is prime. Otherwise, the number is not a prime.

4. C Program for Prime Numbers Using Recursion

*guru99.com

#include <stdio.h>

#include <stdbool.h> 

// recursive function to check if a number

// is prime or not.

bool find_Prime(int num)

{

    static int j = 2; 

    // Base Case

    if (num == 0 || num == 1)

    {

        return false;

    } 

    // Recursive Case

    if (num == j)

        return true; 

    // check if num is divisible by any number

    if (num % j == 0)

    {

        return false;

    }

    j++; 

    // recursive function call.

    return find_Prime(num);

int main()

{

    // test case 1

    int num = 30;

    if (find_Prime(num))

    {

        printf(“%d is a Prime number\n”, num);

    }

    else

    {

        printf(“%d is not a Prime number \n”, num);

    }

    // test case 2

    num = 2;

    if (find_Prime(num))

    {

        printf(“%d is a Prime number\n”, num);

    }

    else

    {

        printf(“%d is not a Prime number \n”, num);

    }

    return 0;

}

Output:

30 is not a Prime number
2 is a Prime number

Explanation

This c program for prime numbers utilizes the recursion technique. Here, the find_Prime function takes the input. The base case starts by checking if the input is 0 or 1. If it happens so, the number is not prime. Then the recursion occurs by checking its divisibility by j that starts from 2. If it’s divisible, then it’s not a prime number. If j reaches the number, that means the number is prime.

5. C program for Prime Numbers within a Range

#include <stdio.h>

#include <math.h>

int isPrime(int n) {

    if (n <= 1) return 0;

    for (int i = 2; i <= sqrt(n); i++) {

        if (n % i == 0) return 0;

    }

    return 1;

}

int main() {

    int start, end;

    printf(“Enter the range (start and end): “);

    scanf(“%d %d”, &start, &end);

    printf(“Prime numbers between %d and %d are:\n”, start, end);

    for (int i = start; i <= end; i++) {

        if (isPrime(i)) {

            printf(“%d “, i);

        }

    }

    printf(“\n”);

    return 0;

}

Output:

Enter the minVal & maxVal Values: 10 20
Prime numbers between 10 and 20 are: 11 13 17 19

Explanation

This is a c program to check prime or not for a range of numbers. Here the range is 10 to 20. The program uses a ‘for loop’ that iterates through each number from the left value to right value.

The program checks and prints the prime numbers within a user-specified range. The isPrime function checks if a number is prime or not. So, it uses an iteration from 2 up to the square root of n. If any number within the range becomes perfectly divisible, that means it’s not a prime number.  The function returns 0. When the number becomes not divisible by any integer from 2 to its square root, the function returns 1. That means the number is prime.

6. C program for Prime Numbers by Skipping Even Iterations

#include <stdio.h>

#include <math.h>  // For square root function

int main() {

    // Declare variables

    int num, i, count = 0;

    // Input number to check

    printf(“Enter a number: “);

    scanf(“%d”, &num);

    // Check if num is less than or equal to 1 or even (except for 2)

    if (num <= 1) {

        printf(“Not Prime\n”);

        return 0;  // Exit the program if num is less than or equal to 1

    }

    if (num == 2) {

        printf(“Prime\n”);

        return 0;  // 2 is prime, exit the program

    }

    // Loop from 3 to sqrt(num), checking only odd numbers

    for (i = 3; i <= sqrt(num); i += 2) {  // Step 2 to skip even numbers

        if (num % i == 0) {  // If divisible by i

            count++;  // Increment count

            break;    // Exit the loop early

        }

    }

    // If count is greater than 0, it’s not prime

    if (count > 0) {

        printf(“Not Prime\n”);

    } else {

        printf(“Prime\n”);

    }

    return 0;

}

Output:

Enter a number: 13Prime
Enter a number: 20Not Prime

Explanation

Skipping even numbers except 2 can reduce the number of checks by half. So, in this case, only odd numbers will be checked. 

So, in this program, a number equal to or less than 1 will be classified as a non-prime number, and the program will exit. If the number is 2, it will be a prime number, and the program will exit. 

Now, for the numbers greater than 2, the iteration will start from 3 and end up at the input’s square. The loop is increased by 2 (i+=2) to check the odd numbers as the divisor. If any of these odd numbers divide the input, that means the number is not prime. If the odd numbers go up to the square root of the input, but any of these odd numbers can’t divide the input perfectly, that means it’s a prime number.

7. C program for Prime Numbers through Square Root Method

#include <stdio.h>

#include <math.h>

int main() {

    int n, isPrime = 1;

    printf(“Enter a number: “);

    scanf(“%d”, &n);

    if (n <= 1) {

        isPrime = 0;

    } else {

        for (int k = 2; k <= sqrt(n); k++) {

            if (n % k == 0) {

                isPrime = 0;

                break;

            }

        }

    }

    if (isPrime) {

        printf(“%d is a prime number.\n”, n);

    } else {

        printf(“%d is not a prime number.\n”, n);

    }

    return 0;

}

Output:

Enter a number: 15
15 is not a prime number.
Enter a number: 11
11 is a prime number.

Explanation

This program reduces the range of divisors for the square root of the number. It optimizes the checking process and reduces the computation time for large numbers. 

This program used the square root function (sqrt()) and math library (math.h) to perform the computation. The user should enter an integer variable n as input. If n is equal to or less than 1, it will be declared a non-prime number (isPrime = 0).

For the numbers greater than 1, the square root optimization is applied. It iterates from 2 (k=2) to the square root of n. If n is divisible by k (n % k ==0), the isPrime will be flagged as 0. The loop will be broken here, and the number will be considered not prime. For the opposite situation, isPrime will print a number that would be a prime number.

8. C program for Prime Numbers Using Sieve of Eratosthenes

#include <stdio.h>

#include <stdbool.h>

#include <string.h> 

// function to find all the

// prime numbers from 1 to num.

void find_Prime(int num)

{    

    // initialize all elements of 

    // the array isPrime as true i.e., 1.

    // An element of the array will 

    // be updated to false, if it is not prime.

    bool isPrime[num + 1];

    memset(isPrime, true, sizeof(isPrime));

    for (int i = 2; k * k <= num; k++)

    {

        // if isPrime[k] is not updated,

        // then it is a Prime.

        if (isPrime[k] == true)

        {

            // update all the multiples of 

            // k as false, starting from 

            // its square upto num

            for (int i = k * k; i <= num; i += k)

                isPrime[i] = false;

        }

    } 

    // print the Prime numbers.

    for (int k = 2; k <= num; k++)

        if (isPrime[k])

            printf(“%d, “, k);

int main()

{

    int num = 20;

    printf(“Following are the Prime numbers smaller “);

    printf(” than or equal to %d “, num);

    printf(“\n”);

     // function call

    find_Prime(num);

    return 0;

}

Output:

The Following are the Prime numbers smaller than or equal to 20:
2, 3, 5, 7, 11, 13, 17, 19

Explanation

The above programming is based on the sieve of Eratosthenes method. Here, a boolean type array has been taken as a sample. The elements of this array are true. That means all the elements are prime numbers. If an element becomes false, that indicates a nonprime number. Also, here is an iteration loop that begins from 2. This loop marks all the multiples of 2 that are equal to or greater than 2’s square as false. The process will be repeated up to √num. Finally, all the true elements become the prime numbers.

Re-sharpen the C Programming Skill with the MCA Program

C programming is a vital topic in computer science. It’s the basis to learn any other programming language in the future. So, individuals interested in C programming should take a professional course like the Online MCA Programme – Manipal University Jaipur. This program comes with both practical and theoretical exposure to C programming. Also, it provides knowledge of advanced topics like data structures, database management systems, software engineering, etc. Some of the key features of this programme are –

Conclusion

These basic techniques of the C program for prime numbers help individuals efficiently find out whether a number is prime or not. All of the codes include a simple trick. It is to check the divisibility of the given input by 2. Now, to stay ahead of programming, it’s vital to learn more concepts of C.

Frequently Asked Questions

What is a prime number?

Prime numbers are those that are only divisible by 1 and themselves, such as 2, 3, 5, 7, 9, etc.

What is the easiest C program for prime numbers?

The simple iterative method is the easiest way to find prime numbers with a C program.

Can negative numbers become prime?

No, negative numbers can’t be prime. Only positive integers can be prime.

Enquiry

Fill The Form To Get More Information


Trending Blogs

Leave a Comment