0

I have to find prime numbers for t cases. Examples of input / output below:

Input:
2
1 10
3 5

Output:
2
3
5
7

3
5

Notice the space between the answers as well.

#include <iostream>
#include <cmath>

bool prime (int x, int y);

using namespace std;

int main()
{
    int t, x, y;
    cin >> t;
    for(int i = 0; i < t; i++)
        cin >> x >> y;
    for(int i = 0; i < t; i++){
        for (int i = x; i <= y; i++)
            cout << prime(x, y) << endl;
    }
    return 0;
}

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

My program outputs only 1 all the time, why is that?

user3002211
  • 181
  • 2
  • 3
  • 11
  • t means the amount of test cases <= 10. For example, in the example it's 2, means I have to output the prime numbers in 2 intervals. – user3002211 Nov 20 '13 at 18:22
  • You have a function that returns `true` if any number in the range is prime, and you keep calling that and printing the result. Perhaps you should find the set of prime numbers and print each of those. – Mike Seymour Nov 20 '13 at 18:25
  • 1
    I don't know how much it will affect your program, but I would recommend changing your inner loop in `main()` to use a variable name other than `i`. It's just good practice to not overshadow variables like that. – jonhopkins Nov 20 '13 at 18:25
  • better to use the [offset sieve of Eratothenes](http://stackoverflow.com/a/19641049/849891). C code [here](http://stackoverflow.com/a/9557173/849891). You will have to know the range of your tests in advance, or you'll have to extend the core array as needed. – Will Ness Nov 22 '13 at 07:21

1 Answers1

3

You are outputting the result of prime(x, y), which is a bool. This will always be zero or one.

Jim Garrison
  • 4,199
  • 4
  • 25
  • 39