Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- using namespace std;
- int isPrime(int n)
- {
- if (n==1) return -1; //The number ain't prime or composite if it's 1
- for (int i=2; i < sqrt(n) + 1; i++) //It's sufficient to check all factors between 2 to sqrt(n)
- {
- if (not (n%i) ) //This is the same thing as writing n%i==0
- return 0;
- }
- return 1; //Note that we reach here iff the program has passed through the above loop
- }
- int main()
- {
- /* This part should be clear to you */
- int n = 1;
- while (n != 0){
- cout << "Enter a number(or 0 to quit): ";
- cin >> n;
- switch(isPrime(n)){
- case 1: cout << "The number is prime. \n"; break;
- case 0: cout << "The number is composite. \n"; break;
- case -1: cout << "The number ain't prime or composite. \n"; break;
- }}
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement