Pages

Thursday, March 27, 2025

Check if a Number is Prime(OPTIMIZED)

#include <iostream>
#include <cmath>
using namespace std;
// check if a number is prime or not (OPTIMIZED)
int main(){
    int n = 13;
    bool isPrime = true;

    for (int i = 2; i <= sqrt(n); i++)
    {
        if(n % i == 0) { // i is a factor of n; i completely divides n; n is non-prime
            isPrime = false;
            break;
        }
    }

    if(isPrime){
        cout << "It is a Prime Number " << endl;

    } else {
        cout << "It is not a Prime number " << endl;
    }
   
   

    return 0;

}

No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...