Advertisement
agnishom

primality_by_trial.cpp

Oct 11th, 2014
416
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. int isPrime(int n)
  7. {
  8.     if (n==1) return -1; //The number ain't prime or composite if it's 1
  9.     for (int i=2; i < sqrt(n) + 1; i++) //It's sufficient to check all factors between 2 to sqrt(n)
  10.     {
  11.         if  (not (n%i) ) //This is the same thing as writing n%i==0
  12.         return 0;
  13.     }
  14.     return 1; //Note that we reach here iff the program has passed through the above loop
  15. }
  16.  
  17. int main()
  18. {
  19.     /* This part should be clear to you */
  20.     int n = 1;
  21.     while (n != 0){
  22.         cout << "Enter a number(or 0 to quit): ";
  23.         cin >> n;
  24.         switch(isPrime(n)){
  25.             case 1: cout << "The number is prime. \n"; break;
  26.             case 0: cout << "The number is composite. \n"; break;
  27.             case -1: cout << "The number ain't prime or composite. \n"; break;
  28.         }}
  29.     return 0;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement