Pages

Monday, March 31, 2025

Check if Prime or not in Functions in C++

 bool isPrime(int n) {

    if( n==1 ) {
        return false;
    }
    for(int i =2; i<= n-1; i++){
        if(n%i == 0) { // non-prime
            return false;
           
        }
    }

    return true;
}


bool isPrime2(int n) {
    if(n == 1){
        return false;
    }
    for(int i = 2; i*i <= n; i++){
        if(n % i == 0) {
            return false;
        }
    }
    return true;
}
int main(){
    cout << isPrime2(4) << 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...