Find all prime numbers from 1 to 1000. This is what I have done until now

closed account (E607ko23)
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
#include<iostream>
#include <cstdlib>

using namespace std;

int main()
{
 int count=0;
 int number;
 cout<<"Enter an Integer:";
 cin>>number;

  for(int i=1;i<=number;i++)
  {
	   if(number%i==0)
	   {
			count++;
	   }
  }
     if(count==2)
  	 cout<<number << " is prime" << endl;
     else
     cout<<number <<" is not prime " << endl;
  system("PAUSE");
  return(0);
}

Last edited on
whats the input for?
if you just have to find all the prim numbers in the range of 0 to 1000, all you need is std::cout
closed account (E607ko23)
What I have done is to ask the user to input a particular number and check if it is prime or not. Now I want to display the prime numbers between 0 to 1000, but I can't make it work.
i'd start with a for loop from 1 to 1000 fisrt
closed account (E607ko23)
I've tried it, but still there is something wrong with my code

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
#include<iostream>
#include <cstdlib>

using namespace std;

int main()
{
 int count=0;
 for(int i=1;i<=1000;i++)
 {
  for(int j=1;j<=i;i++)
  {
	   if(i%j==0)
	   {
			count++;
	   }
  }
     if(count==2)
  	 cout<<i << " is prime" << endl;
     else
     cout<<i <<" is not prime " << endl;
 }
  system("PAUSE");
  return(0);
}
Last edited on
On line 11: you increase i instead of j

Btw: to make it faster you may want break; if count > 2
you also want to reset count before line 11.
btw i%j == 0 is not the best way to check prim numbers.
e.g. if x % 2 != 0 and x % 3 != 0, x % 6 will also be != 0
but you can think about that once it's working
Could write up a quick sieve. Array of bool, set all to be true at first. Change each number divisible by 2 and greater than 2 to be false. Go to three, is it prime? If yes, leave true and set all multiples of 3 to be false. If no, set to false. Find next true element, this is prime. Mark all multiples of this to be false. Continue this until there's no more unmarked spots to move forward to.
closed account (E607ko23)
Thank you for your help guys. I came up with the solution.
Here's what I came up with:

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
#include <iostream>

using namespace std;

bool prime;

int main(int argc, char const *argv[])
{
	for(int i = 1; i <= 1000; i++){
		bool prime = true;

		for(int j = 2; j < i; j++){
			if(i % j == 0 || i == j){
				prime = false;
				break;
			}
		}

		if(prime == true){
			cout << i << " is prime." << endl;
		}
	}

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