Skip to main content

Featured

C Program to Check Prime Number Using Efficient Logic

  Introduction A prime number is a number that has exactly two distinct positive divisors: 1 and itself. In this program, we check whether a given number is prime or not using a simple and efficient logic. This type of program is commonly used in mathematics, competitive programming, and basic algorithm learning for beginners in C programming. Problem Statement The task is to write a C program that determines whether a given integer is a prime number or not. The program takes a single integer input from the user and analyzes its divisibility. If the number has no divisors other than 1 and itself, it should be identified as a prime number; otherwise, it is not prime. This problem is important in number theory and has practical relevance in areas such as cryptography, data validation, and algorithm design.  Algorithm / Logic Explanation To check whether a number is prime, we need to verify that it is not divisible by any number other than 1 and itself. The algorithm follows a si...

C Program: Prime Number Check

C Program: Prime Number Check

๐Ÿ”ท C Program: Prime Number Check

#include<stdio.h>
int main( )
{
    int num, count = 0;
    printf("Enter the number:\n");
    scanf("%d", &num);

    if(num <= 1)
    {
        printf("%d is not a prime number:\n", num);
    }
    else
    {
        for(int i = 2; i <= num / 2; i++)
        {
            if(num % i == 0)
            {
                count++;
                break;
            }
        }

        if(count == 0)
        {
            printf("%d is a prime number:\n", num);
        }
        else
        {
            printf("%d is not a prime number:\n", num);
        }
    }
}
  

๐Ÿ“˜ Explanation:

This C program checks if a number is prime or not.

๐Ÿ‘‰ A **prime number** is a number greater than 1 that is divisible only by 1 and itself.

๐Ÿ”ธ First, the user enters a number.
๐Ÿ”ธ If the number is less than or equal to 1, it's not prime.
๐Ÿ”ธ If the number is greater than 1, the program checks if it has any divisors (from 2 to num/2).
๐Ÿ”ธ If any divisor is found, `count` is incremented, and the loop breaks early for efficiency.
๐Ÿ”ธ Finally, if no divisors are found (`count == 0`), it's a prime number.

๐Ÿ” Sample Output:

Enter the number:
7
7 is a prime number:

Enter the number:
10
10 is not a prime number:

Enter the number:
1
1 is not a prime number:
    

๐Ÿท️ Keywords:

C program to check prime number, prime number logic in C, beginner C programs, isPrime function, modulus operator in C, number theory in C

Comments

Popular Posts

๐ŸŒ™