The main idea: given two numbers, it is required to produce all the prime numbers between these two numbers.
Two digits m and N, the range is as follows:
The input begins with the number T of test cases in a single line (t<=10). In the next T lines there are two numbers m and N (1 <= m <= n <= 1000000000, n-m<=100000) separated b Y a space.
Seemingly simple topics, in fact, is not simple, the general method of determining the number of prime numbers is to see whether the numbers n can be 2 to square root n between the number of the divide, if not, then is prime, of course, here so write the program will be timed out.
Look-up table method is also not good, if the first generation of all the quality tables, then the memory is too large, can not save. The method of interval culling is generally used now.
The fastest thing I know at the moment is the two-time interval culling method:
1 produces a prime number between 2 and 32000 (32000 squared is greater than 1E9), as a mass table (the addition of this table is also to accelerate)
2 again produces all prime numbers between N to M
How to produce a quality table? This is used to search forward, remove the number of not eligible, avoid excessive duplication of calculation, with a point dynamic programming flavor.
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
#include <iostream> #include <vector> #include <string.h> using namespace std;
Class Primenumbergenerator {const static int max_num = 32000;
int Primes[max_num];
int segprimes[100000];
Public:primenumbergenerator () {memset (PRIMES, 0, sizeof (PRIMES));
int j = 0; for (int i = 2; i < Max_num i++) {if (!
Primes[i]) {primes[j++] = i;
for (int k = i*2 k < max_num k+=i)//Not k++ note {//written k = i+1, headache error!!!
Primes[k] = 1;
}} primes[j++] = Max_num;
}//This does not need to use the function bool Isprimenum (int num) {if (2 = num) return true;
int i = 0; for (; Primes[i] * primes[i] <= num && num% primes[i];
i++); return max_num!= primes[i] && NUM% PRIMES[i]!= 0;
} void Getsegprimes (int a, int b) {memset (segprimes, 0, sizeof (segprimes));/Every time you need memset for (int i = 0; Primes[i]*primes[i] <= b;
i++)//error written I <= b-a {int am = a/primes[i]; for (int d = am; d * Primes[i] <= b d++) {if (d > 1 && d * primes[i) >=
a) segprimes[d*primes[i]-a] = 1;
}//There's no less judgment condition d>1} void Judgeprimes () {int a = 0, b = 0;
int T = 0;
cin>>t;
while (t--) {cin>>a>>b;
if (a < 2) a = 2;
Getsegprimes (A, b); for (int i = A; I <= b;
i++) {if (0 = segprimes[i-a]) cout<<i<<endl;
} cout<<endl;
}
}
}; int main () {primenumbergenerator pri;
Pri.judgeprimes ();
return 0; }