Is this seen as an in efficient prime number generator. It seems to me that this is pretty efficient. Is it the use of the stream that makes the program run slower?
I am trying to submit this to SPOJ and it tells me that my time limit exceeded…
#include <iostream> #include <sstream> using namespace std; int main() { int testCases, first, second, counter = 0; bool isPrime = true; stringstream out; cin >> testCases; for (int i = 0; i < testCases; i++) { // get the next two numbers cin >> first >> second; if (first%2 == 0) first++; // find the prime numbers between the two given numbers for (int j = first; j <= second; j+=2) { // go through and check if j is prime for (int k = 2; k < j; k++) { if (j%k == 0) { isPrime = false; break; } } if (isPrime) { out << j << '\n'; } isPrime = true; } out << '\n'; } cout << out.str(); return 0; }
EDIT: The program is supposed to generate prime numbers between the numbers specified in the input. (See here for more details: Prime Generator Problem )
-Tomek
This is one step (skipping even numbers) above the naive algorithm. I would suggest the Sieve Of Eratosthenes as a more efficient algorithm. From the above link:
The algorithm you give is somewhere near O(n^2). The speedup you get by skipping evens isn’t that great because you would find an even number not to be prime on the first test. The sieve has a much greater memory requirement, but the runtime complexity is far superior for large N.