Prime Number Calculator

Alright, so I'm supposed to write a program that spits out all the prime numbers before 10,000, and I have to use a separate function for the math. I created a program that does just that, but I'm not supposed to cout x in the prime function. My professor told me that I'm supposed to return 1 (in the prime function) if x is prime then spit it out (in the main function), or return 0 if x is not prime. I'm not sure how to create an if statement asking if the return value for the prime function is 1 or 0.

Any help is very appreciated.




By the way, the code below is the last working code I created.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
 
using namespace std;
 
int prime(int x, int y) {
for (x=2; x<10000; x++) {
bool prime = true;
for (y =2; y*y<=x; y++) {
if (x % y == 0) {
prime = false;
break;
}
}
if (prime) {
cout << x << " ";
}
}
return x;
}
 
int main(int argc, char *argv[]) {
 
int x,y;
 
prime(x,y);
return 0;
}
I think that you will get plenty of ideas from this thread:
http://www.cplusplus.com/forum/beginner/201756/
1
2
3
4
5
6
7
8
9
int prime(const int &x)
{
        const int y = (x / 2) + 1;
        for (int n = 2; n != y; ++n)
        {
                if (x % n == 0) { return 0; }
        }
        return 1;
}
Last edited on
1
2
3
4
5
6
7
8
bool prime( int n )
{
    for( int i = 2; i * i < n; i++ ) {
        if( n % i == 0 ) return false;
    }

    return true;
}
Topic archived. No new replies allowed.