Prime Numbers using functions

Hi I have this homework question that asks the user to make a program where the computer outputs the prime numbers from 1 to 1000. Can you please take a look at my attempt and tell me where I can improve?

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
31
32
33
34
35
36
#include <iostream>
using namespace std;

void prime_number ();

int main () 
{

prime_number();

return 0;
}


void prime_number ()
{
 int prime=1;
 
 for(int number=1;number<=1000;number++)
 {
 int x=1;

 for(int x=1;x<=number;x++)
{
 if(number%1==0 && number%x==0)
 {
 prime=number;
 cout<<prime<<endl;
 
 }

 }
 
 }
 
}
Last edited on
bump- please help.
Make your program correct, first.
I know the function is wrong hence why I'm posting for help.
Hint* These are fun to do, You left out only the boolean variable that sets a flag if the number can be evenly divided. If the outcome of dividing the outer loop by the inner loop leaves a remainder, set the flag the true, otherwise set it to false and break out of that loop immediatly. Then outside the inner loop test if the flag is true, print the number of the outer loop counter, or 'number' in your case.
Last edited on
I did small changes in your code from above mentioned hint.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void prime_number ()
{
 int prime=0;
 for(int number=1;number<=1000;number++)
 { 
	prime=0;
 	for(int x=2;x<=number/2;x++)
	 {
            if(number%x==0)
  		{
   		         prime=1;
  		         break;
 		}
 	 }

  if(prime!=1)
 	cout<<"Prime number is "<<number<<"\n" ;

 }
 
}
Topic archived. No new replies allowed.