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

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...