Build the Prime Number Checker in C++ with Free Codes

Introduction

Here we are going to Create a Prime Number Checker in C++ and Provide a Free information about basics of this project.

What is Prime Number ?

A Prime Number is a Natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number is only divisible by 1 and the number itself. Some of the first few prime numbers are 2, 3, 5, 7, 11, and 13.

Algorithm for Prime Number Checker

The algorithm to check if a number nnn is prime involves the following steps:

  1. Edge Cases:
    • If n is less than or equal to 1, it is not a prime number.
    • If n is 2 or 3, it is a prime number.
  2. Divisibility Check:
    • If n is divisible by 2 or 3, it is not a prime number.
  3. Loop from 5 to √n:
    • Iterate through all numbers starting from 5 to the square root of n.
    • Check if n is divisible by any of these numbers. If yes, then n is not a prime number.
    • Increment the loop variable by 6 in each iteration, checking for divisibility by iii and i+2i+2i+2.

C++ Code for the Project

Here is the Codes,

#include <iostream>
#include <cmath>

bool isPrime(int n) {
    // Edge cases
    if (n <= 1) return false;
    if (n <= 3) return true;
    
    // Check divisibility by 2 and 3
    if (n % 2 == 0 || n % 3 == 0) return false;
    
    // Check for factors from 5 to √n
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) return false;
    }
    
    return true;
}

int main() {
    int number;
    std::cout << "Enter a number: ";
    std::cin >> number;
    
    if (isPrime(number))
        std::cout << number << " is a prime number.\n";
    else
        std::cout << number << " is not a prime number.\n";
    
    return 0;
}

Prime Number C++ Language

Leave a Comment

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

Scroll to Top