Recently in reviewing the content of data structure, especially how to calculate the time complexity of an algorithm.
In the course of solving the problem, we find an efficient algorithm of prime number solving, and analyze the time complexity of the algorithm.
Algorithm citation: http://blog.csdn.net/aleac/article/details/6430408
void Getprimes (int n)//for the input integer n, print all primes less than n to the screen { bool *temp=new
Bool[n]; for (int i=0;i!=n;++i)//First loop temp[i]=true;
Array to determine if it is a prime number temp[2]=true; for (int i=2;i!=n/2;++i)//second loop { if (Temp[i]) {
int j=2; while (i*j<n )//Multiples of prime numbers are not primes the third loop {
temp[i*j]=false;
++j; }
} } for (int i=2;i!= N;++i)//fourth cycle {
if (Temp[i]) {
++count; &nBsp; if (count% 5 = = 0) {
printf ("%d\n", I); } else {
printf ("%d", I); }
} }
delete[] temp;
}
We begin to analyze the time complexity of the algorithm, which is mainly related to the loop statement.
For the first loop statement, the time complexity is obviously O (n).
The second loop is nested with the third loop, so you need to parse the number of times the statement inside the third loop will be evaluated.
The second cycle makes I from 2 to (n/2-1) cycles (n/2-1), while the inner loop number k is (k=n/i)
So the number of internal statement operations is (N/2 + N/3 + N/4 + ... + n/(n/2-1)) =n (1/2+1/3+1/4+...+1/(n/2-1))
(1/2+1/3+1/4+...+1/(n/2-1)) for the classical harmonic sequence and, there is an approximate summation formula, calculated after (ln (n) +c)
So the time complexity of the statements in the second and third loops is O (N*LN (n))
The time complexity of the fourth loop is obviously O (n).
So the time complexity of the whole algorithm after comparison is O (N*LN (n)).
Compared to the simplest algorithm for prime numbers, such as the following algorithm with TIME complexity O (n^2), the efficiency of the algorithm with Time complexity O (N*LN (n)) is very high.
void Getprimes (int n)//for the input integer n, print all primes less than N to the screen
{
int i, j, num = 0;
for (i = 2, i < n; i++)
{for
(j = 2; J < I; j + +)
{
if (i% j = 0)
{break
;
}
}
if (j >= (i + 1)/2)
{
num++;
if (num% 5 = = 0)
{
printf ("%d\n", I);
}
else
{
printf ("%d", I);
}
}}
}