http://www.geeksforgeeks.org/primality-test-set-1-introduction-and-school-method/
http://www.geeksforgeeks.org/primality-test-set-2-fermet-method/
http://www.geeksforgeeks.org/segmented-sieve/
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5,
bool
isPrime(
int
n)
{
// Corner case
if
(n <= 1)
return
false
;
// Check from 2 to n-1
for
(
int
i=2; i<n; i++)
if
(n%i == 0)
return
false
;
return
true
;
}
Optimized School Method
We can do following optimizations:
We can do following optimizations:
- Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.
- The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)
bool
isPrime(
int
n)
{
// Corner cases
if
(n <= 1)
return
false
;
if
(n <= 3)
return
true
;
// This is checked so that we can skip
// middle five numbers in below loop
if
(n%2 == 0 || n%3 == 0)
return
false
;
for
(
int
i=5; i*i<=n; i=i+6)
if
(n%i == 0 || n%(i+2) == 0)
return
false
;
return
true
;
}
http://www.geeksforgeeks.org/primality-test-set-2-fermet-method/
This method is a probabilistic method and is based on below Fermat’s Little Theorem.
Fermat's Little Theorem: If n is a prime number, then for every a, 1 <= a < n, an-1 ≡ 1 (mod n) Example: Since 5 is prime, 24 ≡ 1 (mod 5), 34 ≡ 1 (mod 5) and 44 ≡ 1 (mod n) Since 7 is prime, 26 ≡ 1 (mod 7), 36 ≡ 1 (mod 7), 46 ≡ 1 (mod 7) 56 ≡ 1 (mod 7) and 66 ≡ 1 (mod 7) Refer this for different proofs.
If a given number is prime, then this method always returns true. If given number is composite (or non-prime), then it may return true or false, but the probability of producing incorrect result for composite is low and can be reduced by doing more iterations.
Below is algorithm:
// Higher value of k indicates probability of correct
// results for composite inputs become higher. For prime
// inputs, result is always correct
1) Repeat following k times:
a) Pick a randomly in the range [2, n ? 2]
b) If an-1 ≢ 1 (mod n), then return false
2) Return true [probably prime].
// C++ program to find the smallest twin in given range #include <bits/stdc++.h> using namespace std; /* Iterative Function to calculate (a^n)%p in O(logy) */ int power( int a, unsigned int n, int p) { int res = 1; // Initialize result a = a % p; // Update x if x >= p while (n > 0) { // If n is odd, multiply x with result if (n & 1) res = (res*a) % p; // n must be even now n = n>>1; // n = n/2 a = (a*a) % p; } return res; } // If n is prime, then always returns true, If n is // composite than returns false with high probability // Higher value of k increases probability of correct // result. bool isPrime(unsigned int n, int k) { // Corner cases if (n <= 1 || n == 4) return false ; if (n <= 3) return true ; // Try k times while (k>0) { // Pick a random number in [2..n-2] // Above corner cases make sure that n > 4 int a = 2 + rand ()%(n-4); // Fermat's little theorem if (power(a, n-1, n) != 1) return false ; k--; } return true ;
Time complexity of this solution is O(k Log n). Note that power function takes O(Log n) time.
|
Given a number n, print all primes smaller than n. For example, if the given number is 10, output 2, 3, 5, 7.
A Naive approach is to run a loop from 0 to n-1 and check each number for primeness. A Better Approach is use Simple Sieve of Eratosthenes.
void
simpleSieve(
int
limit)
{
// Create a boolean array "mark[0..limit-1]" and
// initialize all entries of it as true. A value
// in mark[p] will finally be false if 'p' is Not
// a prime, else true.
bool
mark[limit];
memset
(mark,
true
,
sizeof
(mark));
// One by one traverse all numbers so that their
// multiples can be marked as composite.
for
(
int
p=2; p*p<limit; p++)
{
// If p is not changed, then it is a prime
if
(mark[p] ==
true
)
{
// Update all multiples of p
for
(
int
i=p*2; i<limit; i+=p)
mark[i] =
false
;
}
}
// Print all prime numbers and store them in prime
for
(
int
p=2; p<limit; p++)
if
(mark[p] ==
true
)
cout << p <<
" "
;
}
Problems with Simple Sieve:
The Sieve of Eratosthenes looks good, but consider the situation when n is large, the Simple Sieve faces following issues.
The Sieve of Eratosthenes looks good, but consider the situation when n is large, the Simple Sieve faces following issues.
- An array of size Θ(n) may not fit in memory
- The simple Sieve is not cache friendly even for slightly bigger n. The algorithm traverses the array without locality of reference
Segmented Sieve
The idea of segmented sieve is to divide the range [0..n-1] in different segments and compute primes in all segments one by one. This algorithm first uses Simple Sieve to find primes smaller than or equal to √(n). Below are steps used in Segmented Sieve.
The idea of segmented sieve is to divide the range [0..n-1] in different segments and compute primes in all segments one by one. This algorithm first uses Simple Sieve to find primes smaller than or equal to √(n). Below are steps used in Segmented Sieve.
- Use Simple Sieve to find all primes upto square root of ‘n’ and store these primes in an array “prime[]”. Store the found primes in an array ‘prime[]’.
- We need all primes in range [0..n-1]. We divide this range in different segments such that size of every segment is at-most √n
- Do following for every segment [low..high]
- Create an array mark[high-low+1]. Here we need only O(x) space where x is number of elements in given range.
- Iterate through all primes found in step 1. For every prime, mark its multiples in given range [low..high].
In Simple Sieve, we needed O(n) space which may not be feasible for large n. Here we need O(√n) space and we process smaller ranges at a time (locality of reference)
// This functions finds all primes smaller than 'limit'
// using simple sieve of eratosthenes. It also stores
// found primes in vector prime[]
void
simpleSieve(
int
limit, vector<
int
> &prime)
{
// Create a boolean array "mark[0..n-1]" and initialize
// all entries of it as true. A value in mark[p] will
// finally be false if 'p' is Not a prime, else true.
bool
mark[limit+1];
memset
(mark,
true
,
sizeof
(mark));
for
(
int
p=2; p*p<limit; p++)
{
// If p is not changed, then it is a prime
if
(mark[p] ==
true
)
{
// Update all multiples of p
for
(
int
i=p*2; i<limit; i+=p)
mark[i] =
false
;
}
}
// Print all prime numbers and store them in prime
for
(
int
p=2; p<limit; p++)
{
if
(mark[p] ==
true
)
{
prime.push_back(p);
cout << p <<
" "
;
}
}
}
// Prints all prime numbers smaller than 'n'
void
segmentedSieve(
int
n)
{
// Compute all primes smaller than or equal
// to square root of n using simple sieve
int
limit =
floor
(
sqrt
(n))+1;
vector<
int
> prime;
simpleSieve(limit, prime);
// Divide the range [0..n-1] in different segments
// We have chosen segment size as sqrt(n).
int
low = limit;
int
high = 2*limit;
// While all segments of range [0..n-1] are not processed,
// process one segment at a time
while
(low < n)
{
// To mark primes in current range. A value in mark[i]
// will finally be false if 'i-low' is Not a prime,
// else true.
bool
mark[limit+1];
memset
(mark,
true
,
sizeof
(mark));
// Use the found primes by simpleSieve() to find
// primes in current range
for
(
int
i = 0; i < prime.size(); i++)
{
// Find the minimum number in [low..high] that is
// a multiple of prime[i] (divisible by prime[i])
// For example, if low is 31 and prime[i] is 3,
// we start with 33.
int
loLim =
floor
(low/prime[i]) * prime[i];
if
(loLim < low)
loLim += prime[i];
/* Mark multiples of prime[i] in [low..high]:
We are marking j - low for j, i.e. each number
in range [low, high] is mapped to [0, high-low]
so if range is [50, 100] marking 50 corresponds
to marking 0, marking 51 corresponds to 1 and
so on. In this way we need to allocate space only
for range */
for
(
int
j=loLim; j<high; j+=prime[i])
mark[j-low] =
false
;
}
// Numbers which are not marked as false are prime
for
(
int
i = low; i<high; i++)
if
(mark[i - low] ==
true
)
cout << i <<
" "
;
// Update low and high for next segment
low = low + limit;
high = high + limit;
if
(high >= n) high = n;
}
}
Note that time complexity (or number of operations) by Segmented Sieve is same as Simple Sieve. It has advantages for large ‘n’ as it has better locality of reference and requires