Hello,when I try to solve the second problem about Prime Generator on the
http://www.spoj.com/[
^] in C++(4.0.0-8),it runs to me a trouble that I can compile and run well on my own computer,but when I sent it to spoj, the result is "wrong answer ".
The problem is:
Input : The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output : For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
My answer is:
#include <iostream>
#include <sstream>
#include <map>
#include <list>
#include <math.h>
using namespace std;
bool isPrime(int num)
{
if(num <= 2)
return num == 2;
else if(num % 2 == 0)
return false;
else
{
int Sqrt = sqrt(num);
for(int i = 3;i<=Sqrt;i+2)
{
if(num%i == 0)
return false;
else
return true;
}
}
return true;
}
list<int> getPrime(int m,int n)
{
list<int> li;
if(1 <= m && m <= n && n <= 1000000000 && n-m<=100000)
{
if(n >= 2)
{
for(int k = m;k<=n;k++)
{
if(isPrime(k))
{
li.push_back(k);
}
}
}
}
return li;
}
int main()
{
stringstream ss;
int t = 0;
cin >> t;
map<int,int> nMap;
int a,b;
if(t >= 0 && t <= 10)
{
while(t-- > 0)
{
cin >> a >> b;
nMap.insert(pair<int,int>(a,b));
}
}
map<int,int>::iterator mi;
int oi = 0;
for(mi = nMap.begin();mi != nMap.end();mi++)
{
list<int> ll = getPrime(mi->first,mi->second);
list<int>::iterator lit;
for(lit = ll.begin();lit !=ll.end();lit++)
{
cout << *lit << endl;
}
cout << endl;
}
}
What's the problem in my codes,how can I fix it,please help me,thank you!
I'm very appreciate if you can tell me how to optimaze my code's performance~