Monday, March 20, 2017

Primality Checking

/*  Bismillahir Rahmanir Rahim
    Time Complexity: O(sqrt(n)/2)
*/
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n, i;

bool isPrime(int n){
    if(n<2 || (n!=2 && n%2==0)) return false;
    else{
        for(i=3; i*i<=n; i+=2){
            if(n%i==0) return false;
        }
    }
    return true;
}

int main(){
    while(cin>>n){
        if(isPrime(n)) cout<<"Prime"<<endl;
        else cout<<"Not Prime"<<endl;
    }
    return 0;
}

No comments:

Post a Comment