Check if a Number is Prime

This program checks if a given number is prime.

Program in C:


#include <stdio.h>
#include <stdbool.h>

// Function to check if a number is prime
bool isPrime(int num) {
    // Handling special cases
    if (num <= 1) {
        return false;
    }
    if (num <= 3) {
        return true;
    }

    // Check for divisibility from 2 to sqrt(num)
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    
    return true;
}

int main() {
    int number;
    
    // Input number from user
    printf("Enter a number: ");
    scanf("%d", &number);
    
    // Check if the number is prime
    bool prime = isPrime(number);
    
    // Print the result
    if (prime) {
        printf("%d is a prime number.\n", number);
    } else {
        printf("%d is not a prime number.\n", number);
    }

    return 0;
}
        

Output:

Enter a number: 7
7 is a prime number.

 

Explanation:

  1. isPrime Function:
    • bool isPrime(int num): This function takes an integer num as input and returns true if num is a prime number, and false otherwise.
    • It first handles special cases where numbers less than or equal to 1 are not prime (return false).
    • For numbers 2 and 3 (num <= 3), it directly returns true.
    • For other numbers (num > 3), it checks divisibility from 2 up to the square root of num. If num is divisible by any number in this range, it returns false. If no divisors are found, it returns true.
  2. Main Function:
    • int main(): This is the main function where the program starts execution.
    • It prompts the user to enter a number and reads the input using scanf.
    • It calls the isPrime function to check if the entered number is prime.
    • Based on the return value of isPrime, it prints whether the number is prime or not.

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)