Prime Numbers
Table of contents
# Usage
Determine if a given number is a prime number.
# Algorithm 1
# Explanation
Every composite number X has a number p such that .
And a number which is not a composite number is a prime number.
0 and 1 is not prime numbers.
Even numbers except 2 are not prime numbers.
# Time Complexity
# Code
bool isPrime(Int x) {
if (x == 1) return false;
if (x == 2) return true;
if (x % 2 == 0) return false;
Int sqrtX = Int(sqrt(x));
for (Int n = 3; n <= sqrtX; n += 2) if (x % n == 0) return false;
return true;
}
# Algorithm 2
The Sieve of Eratosthenes
# Explanation
Let the max number of input X.
(This algorithm requires X+1 memory.)
- Initialize
vector<bool> isPrime
whose length is X+1 with elementstrue
. - Set 0th and 1st elements to
false
- Compute
sqrtX
. - Execute the following from n = 2 to
sqrtX
- If
isPrime[n]
istrue
, let the number as it is and set all its multiples otfalse
.
# Time Complexity
For building a table
For finding
# Code
#define MAX_X 100000001
vector<bool> isPrime(MAX_X, true);
void eratosthenes(vector<bool> &isPrime) {
Int x = isPrime.size()-1;
Int x_sqrt = int(sqrt(x));
isPrime[0] = isPrime[1] = false;
loop(i,2,x_sqrt+1) {
if (isPrime[i]) {
for(Int j = i*2; j <= x; j += i) {
isPrime[j] = false;
}
}
}
}
isPrime[31]; // -> true
Shun
Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!