Basic Prime Checker, C++
Exactly what it sounds like.
1#include <iostream>
2#include <cmath>
3
4using std::cout;
5using std::cin;
6
7int main() {
8
9 int myNumber = 0;
10 bool prime = true;
11
12 //The user is prompted to input a positive integer.
13 cout << "Input a positive integer: ";
14 //The user inputs a positive integer.
15 cin >> myNumber;
16
17 /*
18 * The program checks for special cases at the beginning to simplify the process.
19 * If the number is divisible by any single-digit prime, the number is not prime.
20 */
21 if(myNumber == 0 || myNumber == 1){prime = false;}
22 if ( myNumber > 2 && myNumber % 2 == 0 ) {prime = false;}
23 if ( myNumber > 3 && myNumber % 3 == 0 ) {prime = false;}
24 if ( myNumber > 5 && myNumber % 5 == 0 ) {prime = false;}
25 if ( myNumber > 7 && myNumber % 7 == 0 ) {prime = false;}
26
27 //If the number passes that test, continue checking.
28 if(prime){
29 /*
30 *The program only needs to check up to the square root of myNumber because
31 * if myNumber is not prime, it can be factored into i*i.
32 */
33 for (int i = sqrt(myNumber); i > 3; i--)
34 {
35 if(prime){
36 if(myNumber % i == 0){
37 prime = false;
38 }
39 }else{
40 //No need to keep looping if we've already determined it's not prime.
41 break;
42 }
43 }
44 }
45
46 //Feedback to the user before the program ends.
47 if(prime){
48 cout << myNumber << " IS prime!";
49 }
50 else{
51 cout << myNumber << " is NOT prime!";
52 }
53
54 return 0;
55}