Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.77/5 (5 votes)
See more:
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:
SQL
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:
C++
#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~
Posted
Comments
Sergey Alexandrovich Kryukov 15-May-13 11:34am    
Don't you thing that your activity at that site assume that you do it all fully independently? Addressing to this forum should be considered cheating. Why would we help you?

(By the way, your code is pretty dirty, pain to look at. Improve naming, readability, structure, get rid of you hard-coded immediate constants...)

—SA
tiancehngbo 16-May-13 10:00am    
I'm sorry.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900