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

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