prime number test.


#include <iostream>
using std::cin;
using std::cout;
using std::endl;



int main()
{
int number;
int count=0;

while (true)
{
cin >> number;
for(int a=1; a<=number; a++)
{
if(number % a ==0)
{
count++;

}
}

if(count==2)
{
cout<< "1" << endl;
}
else
{
cout<< "0" <<endl;
}

}

}
..................................................................................
above code is supposed to give 0 for prime number and 1 for non prime number. i added while loop so that the user can input numbers more than once. this code works only once..after that it gives only 0..even if the number entered is prime.
Last edited on
I think what you try, is this
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
#include<iostream>

using namespace std;
int main()
{
	int numero, aux;
	double resto;
	cout << "ingrese el numero" << endl;
	cin >> numero;
	cout << "1, 2, 3, 5, 7,";
	for (int i = 2; i <= numero; i++)
	{
		if (i % 2==0 || i % 3==0 || i % 5==0 || i % 7==0)
		{
			aux = 1;
		}
		else
		{
			aux = 0;
		};
		if (aux==0)
		{
			cout << " "<<i <<" ,";

		};
		

	};
	getchar();
	return 0;
}
@flony1
Your code prints out prime numbers from to the number specified by the user. There are two issues:

1) That isn't what the OP asked for,
2) Your algorithm is incorrect. There exist numbers that are not divisible by 2, 3, 5 or 7 that are not prime.

@OP
You need to reset count to 0 for each iteration of the loop.

Also, although your algorithm is correct, there are a few issues that I have:

1) Make it into a function, and if, for any values tested, there is a zero remainder, return false. The way you do it now requires that exactly two numbers divide number, so it will say a number like 121 is prime (even though it isn't),
2) Not really an issue, but you only need to check that number is divisible by 2 - sqrt(number), not 2 - number (the actual issue is that you don't want to check if number divides number).
Topic archived. No new replies allowed.