forked from aaronbloomfield/pdr
-
Notifications
You must be signed in to change notification settings - Fork 228
/
primenumber.cpp
36 lines (32 loc) · 1.08 KB
/
primenumber.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Prime number generation code
//
// written by Aaron Bloomfield, 2014
#include <iostream>
using namespace std;
// yes, there are much faster -- and much better -- ways to check if a
// number is prime (see the Sieve of Eratosthenes, for one example),
// but this code will work correctly, it is fairly straightforward,
// and it is fast enough for our purposes in the hash lab
bool checkprime(unsigned int p) {
if ( p <= 1 ) // 0 and 1 are not primes; the are both special cases
return false;
if ( p == 2 ) // 2 is prime
return true;
if ( p % 2 == 0 ) // even numbers other than 2 are not prime
return false;
for ( int i = 3; i*i <= p; i += 2 ) // only go up to the sqrt of p
if ( p % i == 0 )
return false;
return true;
}
int getNextPrime (unsigned int n) {
while ( !checkprime(++n) );
return n; // all your primes are belong to us
}
int main() {
int x;
cout << "Enter number: ";
cin >> x;
cout << x << " is prime: " << checkprime(x) << endl;
cout << "next higest prime: " << getNextPrime(x) << endl;
}