Pages

Thursday, March 27, 2025

check prime no. in C++

 #include <iostream>

using namespace std;
int main(){
    int n = 7;
    bool isPrime = true; // assumes all numbers are prime

    for(int i = 2; i <= n-1; i++){
        if(n % i == 0){ // i is a factor of n; i completely divides n; n is non-prime
            isPrime = false;
            break;
        }
    }
   
    if(isPrime){ // or if(isPrime == true)
        cout << "number is prime " << endl;
    } else{
        cout << "number is not prime" << endl;
    }
   

    return 0;

}

No comments:

Post a Comment

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...