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

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...