0

Find prime numbers in specific interval in specific amount of test cases.

Example is below: Input:

2
1 10
3 5

Output:

2
3
5
7

3
5

Notice the little space between the answer also.

here's my code:

#include <iostream>
#include <cmath>

void prime (int x, int y);

using namespace std;

int main()
{
    int t, x[10], y[10];
    cin >> t;

    for (int i = 0; i < t; i++)
        //for (int j = 0; j < t; j++)
        cin >> x[i] >> y[i];

    while (t > 0){
        for (int i = 0; i < t; i++)
            prime(x[i], y[i]);
        t--;
    }
}

void prime(int x, int y){
    bool prime = true;
    for (int i = x; i <= y; i++){
        for (int j = 2; j <= sqrt(i); j++){
            prime = true;
            if (i % j == 0)
                prime = false;
        }
        if (prime == true)
            cout << i << endl;
    }
    cout << endl;
}

Here's the output I get when I use the same input.

1
2
3
5
7
10

3
5

1
2
3
5
7
10

What am I doing wrong?

user3002211
  • 181
  • 2
  • 3
  • 11
  • use [offset sieve of Eratothenes](http://stackoverflow.com/a/19641049/849891). C code [here](http://stackoverflow.com/a/9557173/849891). – Will Ness Nov 21 '13 at 16:48

2 Answers2

1

You should move prime = true outside of the for loop. You are currently resetting it at every iteration. As far as the printing, you don't need that << endl when you print each line. You only need a space.

quazzieclodo
  • 831
  • 4
  • 10
  • I moved it in the first for() loop and it seems to fix the problem with the primes, but it still executes 3 times for some reason, the first interval is calculated twice, any reason for that? – user3002211 Nov 20 '13 at 19:16
-1

Since no one's pointed it out yet, if you're wondering why you're getting three sets of output instead of two...

while (t > 0){
  for (int i = 0; i < t; i++)
    prime(x[i], y[i]);
  t--;
}

might be better phrased as

for (int i = 0; i < t; i++)
  prime(x[i], y[i]);

(The outer loop is what gives you extra output.)

cbmanica
  • 3,502
  • 7
  • 36
  • 54