rorschack

IsPrime

Mar 26th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4.  
  5. //Checking primality of a number using TRIAL DIVISION METHOD
  6.  
  7. using namespace std;
  8.  
  9. int main() {
  10.     unsigned int n;
  11.     cout << "Enter a Positive decimal number: ";
  12.     cin >> n;
  13.     if(n==0||n==1) {
  14.         cout << endl << n << " is neither prime nor composite.\n";
  15.         return 0;
  16.     }
  17.     for(int i=2;i<=sqrt(n);i++) { //Set i to be less than n if sqrt not available and use the below commented method
  18.         if(n%i==0) {
  19.             cout << endl << n << " is not a prime number.\n";
  20.             return 0;
  21.         }
  22.         /* If sqrt function is not supported or cannot be used, take squares of the factors
  23.         and make sure i is set to be less than n and not its square root.
  24.         *****THIS WILL INCREASE THE TIME COMPLEXITY*****
  25.          else if(i*i>n) {
  26.             cout << endl << n << " is a prime number.\n";
  27.             break;
  28.         }*/
  29.     }
  30.     cout << endl << n << " is a prime number.\n";//Discard the statement if using the above commented method
  31.     return 0;
  32. }
Add Comment
Please, Sign In to add comment