4 / 4
Aug 2016

HI, I made a code which actually show correctly prime numbers but when I'm going to compile it, a judge shows me that my code is wrong. Can you tell me, guys, why judge don't want to accept my code ?

1. //   http://www.spoj.com/problems/PRIME1/
2.    
3.     #include  <iostream>
4.     #include  <cmath>    
5.     using namespace std;
6.     int m,n;
7.     int main()
8.     {
9.         cin >>m>>n;
10.       for(m; m<=n;m++)
11.       {

12.         int p;
13.         int c=1;
14.         for(p=2;p<m-1;p++)
15.         {
16.             if(m%p!=0)
17.              {
18.                  continue;
19.              }
20.             else
21.              {
22.                      c=0;
23.              }
24.         }
25.         if(c==0)
26.         {
27.             cout<<"";
28.         }
29.         else if(m==1) // that is because my code shows number 1 as a prime ,rest is good :slight_smile: 
30.         {
31.          cout <<"";
32.         }
33.     else
34.     {
35.         cout << m << endl;
36.     }
37.       }
38.     return 0;
39.     }
  • created

    Aug '16
  • last reply

    Aug '16
  • 3

    replies

  • 1.1k

    views

  • 2

    users

  • 2

    likes

  • 1

    link

Your code should have an input of the number of cases and loop over the test cases.

I made it and judge shows me that compiling exceed time that I have ,can somebody helps me to make my program faster. I'm fighting with this task almost a week. Now code looks like this

1.     #include <iostream>
2.     #include <cmath>
3.     using namespace std;
4.     short m,n,p;
5.     int main()
6.     {
7.         cin >> p;
8.         while(p>0)
9.         {
10.             p--;
11.         cin >>m;
12.         cin >>n;
13.       for(m; m<=n;m++)
14.       {
15.         int c=1;
16.         for(int p=2;p<m-1;p++)
17.         {
18.             if(m%p!=0)
19.             continue;
20.             else
21.              c=0;
22.         }
23.         if((c==0)||(m==1))
24.             cout<<"";
25.            else
26.         {
27.             cout << m << endl;
28.         }
29.       }
30.         }
31.     return 0;
32.     }

You might find this interesting. Your code currently checks every number between 1 and m-1 if it is a divisor. That’s far too much and that costs a lot of time.

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 21 13d

Want to read more? Browse other topics in C and C++ or view latest topics.